- 浏览: 131228 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
qq466862016:
不错的文章
JDK动态代理与CGLIB代理的对比 -
jinxiongyi:
你好,jpedal pdf转换图片的 画质,怎么提高。。我转 ...
介绍几款PDF转图片的开源工具 -
qqdwll:
转图片消耗的内存还是不小。 有时间得找找有没有更好的办法, 把 ...
介绍几款PDF转图片的开源工具 -
xiaoyao3857:
Thanks for your work!It's help ...
Keeping Eclipse running clean (转载) -
iceside:
图片讲解非常详细,说清了引用复制是怎么回事
Java 值传递的终极解释
原文 http://www.javapractices.com/topic/TopicAction.do?Id=29
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your program, since they :
* are simple to construct, test, and use
* are automatically thread-safe and have no synchronization issues
* do not need a copy constructor
* do not need an implementation of clone
* allow hashCode to use lazy initialization, and to cache its return value
* do not need to be copied defensively when used as a field
* make good Map keys and Set elements (these objects must not change state while in the collection)
* have their class invariant established once upon construction, and it never needs to be checked again
* always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state 。
Immutable objects have a very compelling list of positive qualities. Without question, they are among the simplest and most robust kinds of classes you can possibly build. When you create immutable classes, entire categories of problems simply disappear.
Make a class immutable by following these guidelines :
* ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
* make fields private and final
* force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
* do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
* if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
In Effective Java, Joshua Bloch makes this compelling recommendation :
"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."
It's interesting to note that BigDecimal is technically not immutable, since it's not final.
Example
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your program, since they :
* are simple to construct, test, and use
* are automatically thread-safe and have no synchronization issues
* do not need a copy constructor
* do not need an implementation of clone
* allow hashCode to use lazy initialization, and to cache its return value
* do not need to be copied defensively when used as a field
* make good Map keys and Set elements (these objects must not change state while in the collection)
* have their class invariant established once upon construction, and it never needs to be checked again
* always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state 。
Immutable objects have a very compelling list of positive qualities. Without question, they are among the simplest and most robust kinds of classes you can possibly build. When you create immutable classes, entire categories of problems simply disappear.
Make a class immutable by following these guidelines :
* ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
* make fields private and final
* force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
* do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
* if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
In Effective Java, Joshua Bloch makes this compelling recommendation :
"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."
It's interesting to note that BigDecimal is technically not immutable, since it's not final.
Example
import java.util.Date; /** * Planet is an immutable class, since there is no way to change * its state after construction. */ public final class Planet { public Planet (double aMass, String aName, Date aDateOfDiscovery) { fMass = aMass; fName = aName; //make a private copy of aDateOfDiscovery //this is the only way to keep the fDateOfDiscovery //field private, and shields this class from any changes that //the caller may make to the original aDateOfDiscovery object fDateOfDiscovery = new Date(aDateOfDiscovery.getTime()); } /** * Returns a primitive value. * * The caller can do whatever they want with the return value, without * affecting the internals of this class. Why? Because this is a primitive * value. The caller sees its "own" double that simply has the * same value as fMass. */ public double getMass() { return fMass; } /** * Returns an immutable object. * * The caller gets a direct reference to the internal field. But this is not * dangerous, since String is immutable and cannot be changed. */ public String getName() { return fName; } // /** // * Returns a mutable object - likely bad style. // * // * The caller gets a direct reference to the internal field. This is usually dangerous, // * since the Date object state can be changed both by this class and its caller. // * That is, this class is no longer in complete control of fDate. // */ // public Date getDateOfDiscovery() { // return fDateOfDiscovery; // } /** * Returns a mutable object - good style. * * Returns a defensive copy of the field. * The caller of this method can do anything they want with the * returned Date object, without affecting the internals of this * class in any way. Why? Because they do not have a reference to * fDate. Rather, they are playing with a second Date that initially has the * same data as fDate. */ public Date getDateOfDiscovery() { return new Date(fDateOfDiscovery.getTime()); } // PRIVATE // /** * Final primitive data is always immutable. */ private final double fMass; /** * An immutable object field. (String objects never change state.) */ private final String fName; /** * A mutable object field. In this case, the state of this mutable field * is to be changed only by this class. (In other cases, it makes perfect * sense to allow the state of a field to be changed outside the native * class; this is the case when a field acts as a "pointer" to an object * created elsewhere.) */ private final Date fDateOfDiscovery; }
发表评论
-
介绍几款PDF转图片的开源工具
2011-09-09 00:40 4485最近项目中有个需求需要把PDF转成一张图。经过调查,有 ... -
jadclipse(反编译Eclipse插件)
2011-07-19 19:13 1615Jad Java decompiler plugin for ... -
Java开发时候的内存溢出
2011-07-13 17:33 1156这里以tomcat环境为例, ... -
class loader
2011-07-08 17:23 0Because Class.getResource() eve ... -
Jakarta-Common-BeanUtils使用笔记
2011-07-06 16:55 1296原文转发http://blog.csdn.net/fa ... -
基于MVC模式Struts框架研究
2011-04-13 20:02 1297不做web开发多年了, 可偶尔去面试的时候, 还是 ... -
Java反射与动态代理
2011-04-13 15:08 934这篇文章是 成富 先生在InfoQ上Java 深度历险系列的一 ... -
Java枚举类型
2011-04-04 19:50 748Tiger中的一个重要新特性是枚举构造,它是一种新的Java枚 ... -
Java 值传递的终极解释
2011-03-21 22:49 1935对于Java的值传递, 你真的了解么? Ja ... -
六种异常处理的陋习
2011-03-20 03:21 727你觉得自己是一个Java专 ... -
数组初始化
2011-03-20 02:40 831数组初始化,你觉得简单吗? a.如果你觉得简单,那请看下面的 ... -
Java 实现 hashCode 方法
2011-03-11 17:07 1128原文 http://www.javapractices.com ... -
Java 内部类介绍
2011-02-16 17:14 944转载: http://zhidao.baidu.com/que ... -
Java 中的Clone 学习总结
2011-01-25 18:22 26881. 一个类需要实现clone. 一个最佳实践是它需要实现 C ... -
java 通过流, nio 移动文件或者文件夹
2011-01-04 17:54 1810我们用例子说明java怎样通过不同的方式移动文件或文件夹。 ... -
转 深入探讨SOAP、RPC和RMI
2010-12-17 00:34 1006这篇文章是从网上转下来的。 原文应该是写于2001年。 10 ... -
java 6 中的性能优化
2010-12-07 15:30 1404文章转载自: http://www ... -
创建强健,稳定的 JMS 系统
2010-12-07 15:21 945The most reliable way to produc ... -
Java Modifier Summary
2010-11-12 15:10 839<tbody> <tr> ... -
[ZT] 怎样停止一个线程或者任务
2010-11-12 15:08 958source file http://forward.com. ...
相关推荐
Java类:材料PO,产品PO,中间PO,中间PO的复合主键类(由于是两个一对多形成的多对多,所以,这里只讲一个一对多,另一个是相同的映射方法) //产品类: public class Product { private Integer cpbh; private ...
一、到底要怎么样初始化! 本问题讨论变量的初始化,所以先来看一下Java中有哪些种类的变量。 1. 类的属性,或者叫值域 2. 方法里的局部变量 3. 方法的参数 对于第一种变量,Java虚拟机会自动进行初始...
##-----java.lang.Class类----- 5. 为什么说Class类不能被继承? 6. 为什么说我们不能 new Class()? 7. forName()中执行了什么流程? 8. toString()返回什么? 9. newInstance()中执行了什么? ##-----java.lang....
實踐63:審慎㆞定義和實現immutable classes(不可變類) 213 實踐64:欲傳遞或接收mutable objects(可變對象)之object references 時,請實施clone() 215 實踐65:使用繼承(inheritance)或委託(delegation)來...
如果你需要使用equals方法,或者使用任何基于散列码的集合(HashSet,HashMap,HashTable),请察看一下java doc以确认这个类的equals逻辑是如何实现的。 问题三:String到底变了没有? 没有。因为String被...
样本 核心 Java 示例 1.Comparable Vs Comparator 2.Equal() & HashCode() 契约 3.Runtime Class 4.Uninstantiable Class 5.Immutable Class
Jomni:Java 8的对象映射器 Jomni 是一个 Java 8 库,它可以很容易地在 Java 中将一种类型的对象转换为另一种类型。 它体积小、可扩展,并且是为 Java 8 用 Java 8 编写的。 // build the immutable and ...
Java SE5 and SE6 .................. 2 Java SE6 ......................................... 2 The 4th edition........................ 2 Changes .......................................... 3 Note on the ...
工厂吉尔 用法 sourceCompatibility = 1.8 dependencies { ...} 特征 支持的: 定义可重复使用的工厂 覆盖字段 关联:将字段定义为其他... class, ImmutableMap . of( " make " , " ford " , " convertible " , false ,
│ 高并发编程第二阶段43讲、类加载的过程以及类主动使用的六种情况详细介绍.mp4 │ 高并发编程第二阶段44讲、被动引用和类加载过程的练习巩固训练题.mp4 │ 高并发编程第二阶段45讲、ClassLoader加载阶段发生的...
│ 高并发编程第二阶段43讲、类加载的过程以及类主动使用的六种情况详细介绍.mp4 │ 高并发编程第二阶段44讲、被动引用和类加载过程的练习巩固训练题.mp4 │ 高并发编程第二阶段45讲、ClassLoader加载阶段发生的...
19.2 使用动态特征实现Scala 中的动态调用 397 19.3 关于DSL的一些思考 402 19.4 本章回顾与下一章提要 402 第20章 Scala的领域特定语言 403 20.1 DSL 示例:Scala中XML和JSON DSL 404 20.2 内部DSL...
13.2 Mutable and Immutable Collections 173 13.3 Sequences 174 13.4 Lists 175 13.5 Sets 177 13.6 Operators for Adding or Removing Elements 178 13.7 Common Methods 180 13.8 Mapping a Function 182 13.9 ...
@Value.Immutable public abstract class User { public abstract int id(); public abstract String username(); } 我们可以将其用作: User user = ImmutableUser.builder().id(1).username("olidroide")....
阅读完整的文档,为 // Define abstract value type using interface, abstract class or annotation@Value . Immutablepublic interface ValueObject extends WithValueObject { // extend not-yet-generated ...
PEP 487: Simpler customization of class creation PEP 487: Descriptor Protocol Enhancements PEP 519: Adding a file system path protocol PEP 495: Local Time Disambiguation PEP 529: Change Windows ...
1.1.2. The first class .......................................................................................... 3 1.1.3. The mapping file ...............................................................