Java Immutable Class:如何创建,有哪些优点

Java中很多class都是immutable,像String,Integer等,它们通常用来作为Map的key.

那么在实现自定义的Immutable的Class的时候,应该注意哪些要点呢?

 

a)Class 应该定义成final,避免被继承。

b)所有的成员变量应该被定义成final。

c)不要提供可以改变类状态(成员变量)的方法。【get 方法不要把类里的成员变量让外部客服端引用,当需要访问

成员变量时,换回成员变量的copy】

d)构造函数不要引用外部可变对象。如果需要引用外部可以变量,应该在构造函数里进行defensive copy。


Wrong way to write a constructor:
public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray; // wrong
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller could change the array after calling the
constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
After constructing Numbers are: 1 5

 

Right way to write an immutable class
Right way is to copy the array before assigning in the constructor.

public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray.clone(); // defensive copy
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller cannot change the array after calling the constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
After constructing Numbers are: 1 2


----------------------------------------------Immutable Class Interview Questions----------------------------

Q1) What is an immutable class?

Ans) Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class

Q2) How to create an immutable class?

Ans) To create an immutable class following steps should be followed:

  1. Create a final class.
  2. Set the values of properties using constructor only.
  3. Make the properties of the class final and private
  4. Do not provide any setters for these properties.
  5. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    1. Don't provide methods that modify the mutable objects.
    2. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

E.g.
public final class FinalPersonClass {

      private final String name; 
      private final int age; 
      
      public FinalPersonClass(final String name, final int age) { 
            super(); 
            this.name = name; 
            this.age = age; 
      } 
      public int getAge() { 
            return age; 
      } 
      public String getName() { 
            return name; 
      } 
      
}

Q3) Immutable objects are automatically thread-safe –true/false?

Ans) True. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.

Q4) Which classes in java are immutable?

Ans) All wrapper classes in java.lang are immutable – 
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger

Q5) What are the advantages of immutability?

Ans) The advantages are: 
1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
  4) The best use of the immutable objects is as the keys of a map.


转载自:

【1】Java实现Immutable Class要点

http://blog.csdn.net/kkdelta/article/details/3955399

【2】Immutable Class Interview Questions

http://www.java-questions.com/ImmutableClass_interview_questions.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值