String equals hashcode

package equal;

/**
 * 关于equals  hashCode
 * 
 * @author ZengWenFeng
 * @mobile 13805029595
 * @email 117791303@qq.com
 */
public class A
{
	/** The value is used for character storage. */
	private final char value[] = null;

	/** Cache the hash code for the string */
	private int hash; // Default to 0

	private String code;
	private String name;

	public A(String code, String name)
	{
		this.code = code;
		this.name = name;
	}

	public int hashCode()
	{
		int h = hash;
		if (h == 0 && value.length > 0)
		{
			char val[] = value;

			for (int i = 0; i < value.length; i++)
			{
				h = 31 * h + val[i];
			}
			hash = h;
		}

		return h;
	}

//	public boolean equals(Object anObject)
//	{
//		if (this == anObject)
//		{
//			return true;
//		}
//		
//		if (anObject instanceof String)
//		{
//			String anotherString = (String) anObject;
//			int n = value.length;
//			if (n == anotherString.value.length)
//			{
//				char v1[] = value;
//				char v2[] = anotherString.value;
//				int i = 0;
//				while (n-- != 0)
//				{
//					if (v1[i] != v2[i])
//						return false;
//					i++;
//				}
//				return true;
//			}
//		}
//		
//		return false;
//	}

	public boolean equals(Object obj)
	{
		if (obj == null)
		{
			return false;
		}

		if (this == obj)
		{
			return true;
		}

		if (this.getClass() != obj.getClass())
		{
			return false;
		}

		A a = (A) obj;
		return code.equals(a.code) && name.equals(a.name);
	}

	public static void main(String[] args)
	{
		A obj1 = new A("005129", "zwf");
		A obj2 = new A("005129", "zwf");
		A obj3 = new A("005128", "zwf");

		System.out.println(obj1.equals(obj2));
		System.out.println(obj1.hashCode());
		System.out.println(obj2.hashCode());

		System.out.println("------");
		System.out.println(obj1.equals(obj3));
		System.out.println(obj1.hashCode());
		System.out.println(obj3.hashCode());

		System.out.println("------");
		System.out.println("005129".hashCode());
		System.out.println(new String("005129").hashCode());
		System.out.println("005129".equals(new String("005129")));

		/**
		 * 
		 * 
		true
		2018699554
		1311053135
		------
		false
		2018699554
		118352462
		------
		1420155875
		1420155875
		true
		 * 
		 */
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值