Chinaunix首页 | 论坛 | 博客
  • 博客访问: 53323
  • 博文数量: 27
  • 博客积分: 1505
  • 博客等级: 上尉
  • 技术积分: 304
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-19 13:25
文章分类

全部博文(27)

文章存档

2015年(14)

2014年(4)

2013年(2)

2012年(1)

2011年(4)

2010年(2)

我的朋友

分类: Java

2015-12-05 14:20:12

identityHashCode的官方API说明:
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.
返回的hashCode与默认的hashCode方法返回值一样,无论hashCode方法是否被重载,当hashCode是null时,返回0;

通过实验得知,identityHashCode与Object的hashCode()方法获取的是相同的,即通过内存地址计算得来;

测试代码:
public class HashCodeTest {


public static Bean bean;

public static void testHashCode() {
bean = new Bean();
System.out.println(bean.hashCode());
System.out.println(System.identityHashCode(bean));
}

public static void main(String[] args) {
testHashCode();
}
}


class Bean {
private String test;


public String getTest() {
return test;
}


public void setTest(String test) {
this.test = test;
}


@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((test == null) ? 0 : test.hashCode());
return result;
}


@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Bean other = (Bean) obj;
if (test == null) {
if (other.test != null)
return false;
} else if (!test.equals(other.test))
return false;
return true;
}
}

输出结果:
31(hashCode方法)
705927765(identityHashCode方法

当去掉Bean中的重载方法hashCode后,输出结果为:
705927765
705927765




阅读(462) | 评论(0) | 转发(0) |
0

上一篇:System.getProperties()与System.getenv()的区别

下一篇:没有了

给主人留下些什么吧!~~