一.
注意hashCode与equals方法在HashSet中的应用(HashSetTest3)
public class HashSetTest {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Set set =new HashSet();//Set是一个不包含重复元素的 collection
set.add("zhangsan");
set.add("lisi");
set.add("wangwu");
System.out.println(set.add("zhangsan"));//添加重复元素...失败!
System.out.println(set.size());//Set集合中元素个数
}
}
//没写hashCode与equals方法之前
public class HashSetTest2 {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Set set = new HashSet();
People p1 = new People("zhangsan");
People p2 = new People("lisi");
People p3 = new People("wangwu");
People p4 = new People("zhangsan");
People p5 = new People("zhangsan");
set.add(p1);
set.add(p2);
set.add(p3);
set.add(p4);
set.add(p5);
System.out.println(set.size());
}
}
class People {
String name;
public People(String name) {
this.name = name;
}
}
//没写hashCode与equals方法之后
public class HashSetTest3 {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Set set =new HashSet();
Student p1=new Student("zhangsan");
Student p2=new Student("lisi");
Student p3=new Student("wangwu");
Student p4=new Student("zhangsan");
Student p5=new Student("zhangsan");
set.add(p1);
set.add(p2);
set.add(p3);
set.add(p4);
set.add(p5);
System.out.println(set.size());
}
}
class Student{
String name;
public Student(String name){
this.name=name;
}
//用系统生成的方法
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((name == null) ? 0 : name.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;
final Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
/*//自己写的方法
@Override
public int hashCode() {
System.out.println("hashCode executed!");
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
System.out.println("equals executed!");
if (this == obj) {
return true;
}
if (obj instanceof Student) {
Student s = (Student) obj;
return name.equals(s.name);
}
return false;
}*/
}