上次面试时被面试官被到这个问题,当时没有答对,后来自己研究了下,到今天总算是弄明白了。
先定义一个类,当然既然要放入到hashSet中当然要重写hashcode()方法和equal()方法。
package com.map.test;
/**
* Created by 74039 on 2017-02-26.
*/
public class Cat {
private int a;
private String name;
public Cat(int a, String name) {
this.a = a;
this.name = name;
}
public Cat() {
}
@Override
public boolean equals(Object o) {
System.out.println("我是equals方法");
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cat cat = (Cat) o;
if (a != cat.a) return false;
if (!name.equals(cat.name)) return false;
return true;
}
@Override
public int hashCode() {
System.out.println("我是hashcode方法");
int result = a;
result = 31 * result;// + name.hashCode();*/
return result;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
再来写一个测试类,如下
package com.map.test;
import java.util.HashSet;
import java.util.Set;
/**
* Created by 74039 on 2017-02-26.
*/
public class App1 {
public static void main(String[] args) {
Set catSet=new HashSet();
//catSet.add()
Cat cat=new Cat(1,”hello”);
Cat cat2=new Cat(3,”hello”);
Cat cat3=new Cat(1,”hello3”);
Cat cat4=new Cat(3,”hello4”) ;
catSet.add(cat);
System.out.println(“===========”);
catSet.add(cat2);
System.out.println(“===========”);
catSet.add(cat3);
System.out.println(“===========”);
catSet.add(cat4);
System.out.println(catSet.size());
}
}
直接先看程序的运行结果,然后在解析分析:
我是hashcode方法
===========
我是hashcode方法
===========
我是hashcode方法
我是equals方法
===========
我是hashcode方法
我是equals方法
4
控制台打印输出如上信息,可以看到每次添加元素都会调用hashcode方法,而只有当hashcode一样时才会调用equals方法。
说明,在插入元素时会首先调用hashcode方法来判断有无重复,如果没有直接插入,如果有则去比较hashcode重复的对象的equals方法,看equals是否重复,如果equals一样,不会插入,如果equals不一样,则插入。
以上就是我的理解。期待同各位高手经常交流。QQ:740393778