class="article_content clearfix">
class="htmledit_views">
HashCode理解--3
Java 对象 Hashcode 的作用是什么?可以联想class="tags" href="/tags/ShuJuJieGou.html" title=数据结构>数据结构的哈希表(散列表)、哈希函数。Object.hashCode() 就是一个哈希函数,用来计算散列值以实现哈希表这种class="tags" href="/tags/ShuJuJieGou.html" title=数据结构>数据结构。看下哈希表结构:
默认是使用对象的地址计算散列码。
class="language-java">package interview;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
public class Person {
private int age;
private String name;
public Person(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean class="tags" href="/tags/EQUALS.html" title=equals>equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == class="tags" href="/tags/NULL.html" title=null>null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (age != other.age) {
return false;
}
if (name == class="tags" href="/tags/NULL.html" title=null>null) {
if (other.name != class="tags" href="/tags/NULL.html" title=null>null)
return false;
} else if (!name.class="tags" href="/tags/EQUALS.html" title=equals>equals(other.name))
return false;
return true;
}
/*public int hashCode() {
final int prime = 31;
int result = 1;
result = prime*result + age;
result = prime * result + (name == class="tags" href="/tags/NULL.html" title=null>null ? 0 :name.hashCode());
return result;
}*/
public static void main(String[] args) {
Collection<Person> list = new ArrayList<Person>();
Collection<Person> set = new HashSet<Person>();
list.add(new Person(1, "a"));
list.add(new Person(1, "a"));
list.add(new Person(2, "a"));
list.add(new Person(3, "a"));
set.add(new Person(1, "a"));
set.add(new Person(1, "a"));
set.add(new Person(2, "a"));
set.add(new Person(3, "a"));
System.out.println("ArrayList size ==" + list.size());
System.out.println("HashSet size ==" + set.size());
}
}
打印出了如下的结果
ArrayList size == 4
HashSet size == 4
证明p1和p2两个对象还是不相等的
当我们把hashCode注释打开再运行一次
ArrayList size == 4
HashSet size == 3
证明了p1和p2两个对象已经相等
说明:HashCode主要是为了解决集合中元素的冲突问题,默认情况下,使用对象的地址来计算散列码,新建两个new Person(1,“a”)对象,他们在内存中对应不同的地址,因此,认为他们是不相同的,所以会存放在不同的位置,如果新定义了hashcode(),那么他就会认为是相同的两个对象,只是出现hash码冲突,通过函数体中内容来解决冲突。