一概念介绍
1 不可变类的意思是创建该类的实例后,该实例的实例变量是不可改变的。Java提供的8个包装类和String类都是不可变类。
2 创建自定义不可变类要满足以下几个条件。
- 使用private和final修饰符来修饰该类的成员变量。
- 提供带参数的构造器,用于根据传入参数来初始化类里属性
- 仅为该类的成员变量提供getter方法,而不提供setter方法。
- 如有必要,重写Object类中的hashcode和equaIs方法。
二测试不可变类String
1代码示例
public class ImmutableStringTest { public static void main(String[] args) { String str1 = new String("Hello"); String str2 = new String("Hello"); System.out.println(str1 == str2); // 输出false System.out.println(str1.equals(str2)); // 输出true // 下面两次输出的hashCode相同 System.out.println(str1.hashCode()); System.out.println(str2.hashCode()); } }
2运行结果
false
true
69609650
69609650
3结果分析
从运行结果来看,它是根据String对象里的字符序列作为相等的标准,其中hashCode方法也是根据字符序列计算得到的。
三自定义不可变类
1代码示例
public class Address { private final String detail; private final String postCode; // 在构造器里初始化两个实例变量 public Address() { this.detail = ""; this.postCode = ""; } public Address(String detail , String postCode) { this.detail = detail; this.postCode = postCode; } // 仅为两个实例变量提供getter方法 public String getDetail() { return this.detail; } public String getPostCode() { return this.postCode; } //重写equals()方法,判断两个对象是否相等。 public boolean equals(Object obj) { if (this == obj) { return true; } if(obj != null && obj.getClass() == Address.class) { Address ad = (Address)obj; // 当detail和postCode相等时,可认为两个Address对象相等。 if (this.getDetail().equals(ad.getDetail()) && this.getPostCode().equals(ad.getPostCode())) { return true; } } return false; } public int hashCode() { return detail.hashCode() + postCode.hashCode() * 31; } }
2代码分析
当程序创建了Address对象后,同样无法修改Address对象的detail和postCode实例变量。