您的位置:首页 > 编程语言 > Java开发

java基础入门-hashcode与equals方法

2015-08-24 00:00 651 查看
equils方法的特性:

1.自反性,对于任何非空引用x,x.equals(x)返回true

2.对称性,对于任何引用x,y,x.equals(y)返回true,那么y.equals(x)返回true

3.传递性,对于任何应用x,y,z,如果x.equals(y)回返true,以及x.equals(z)回返true,则y.equals(z)回返true

4.一致性,如果x,y,没有变化,则x.equals(y)应该返回同意的结果

5.对于任何非空的x,x.equals(null)返回false

hashcode,散列码,是由对象导出的一个整型值。

但是,对于不同的类,他都有可能重写equals和hashcode方法

我们在平常对比两个对象的时候需要注意这两个地方

下面是详细的代码例子

package com.ray.testobject;

/**
* equals与hashcode
*
* @author ray
* @since 2015-05-02
* @version 1.0
*/
public class Test {
public static void main(String[] args) {
String a = "ok";
String b = new String("ok");
System.out.println(a.equals(b));
// 下面是string里面重写的equils方法
// 可以看见首先对比两个obj是否一致,明显不是同一个字符串
// 然后它里面再次对比字符串里面每个字符,只要认定字符一致,则字符串一致
// public boolean equals(Object anObject) {
// if (this == anObject) {
// return true;
// }
// if (anObject instanceof String) {
// String anotherString = (String)anObject;
// int n = count;
// if (n == anotherString.count) {
// char v1[] = value;
// char v2[] = anotherString.value;
// int i = offset;
// int j = anotherString.offset;
// while (n-- != 0) {
// if (v1[i++] != v2[j++])
// return false;
// }
// return true;
// }
// }

StringBuilder asb = new StringBuilder(a);
StringBuilder bsb = new StringBuilder(b);
System.out.println(asb.equals(bsb));
// 由于StringBuilder没有重写equils方法,所以调用的是object里面的equils方法
// 下面是object里面的方法,他至对比两者指向的对象是否一致,所以返回是false
// public boolean equals(Object obj) {
// return (this == obj);
// }

// 同理,在hashcode方法里面string已经重写, 而stringbuilder却没有
System.out.println("a.hashCode:" + a.hashCode());
System.out.println("b.hashCode:" + b.hashCode());
System.out.println("asb.hashCode:" + asb.hashCode());
System.out.println("bsb.hashCode:" + bsb.hashCode());
}
}


输出:

true
false
a.hashCode:3548
b.hashCode:3548
asb.hashCode:29013258
bsb.hashCode:12830537

由上面的代码可以看见,每个类都有可能重写相应的equals和hashcode方法,所以,

在对比对象的时候必须注意上面两个方法的使用。

版权声明:本文为博主原创文章,未经博主允许不得转载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息