不可变类

一概念介绍

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实例变量。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值