package yu;
import java.util.HashSet;
import java.util.Iterator;
//无序不重复(但是对象要想不重复,要重写以下方法)
public class Main {
public static void main(String[] args) {
HashSet<Student> set=new HashSet<>();
Student stu1=new Student("yu1", "1");
Student stu2=new Student("yu2", "2");
Student stu3=new Student("yu3", "3");
Student stu4=new Student("yu3", "3");//重复的对象
set.add(stu1);
set.add(stu2);
set.add(stu3);
set.add(stu4);
//迭代器遍历
Iterator<Student> it=set.iterator();
while (it.hasNext()) {
Object obj = it.next();
System.out.println(obj);
}
}
}
class Student{
String name;
String id;
super();
this.name = name;
this.id = id;
}
@Override
//Java中所有的类都是继承于Object类,自带tostring方法,输出的是类名和内存首地址,
//通过重写toString方法,得到自己想要的打印结果
public String toString() {
return id+":"+name;}
//通过重写这两个方法实现对象的去重(eclipse可自动生成)
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
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;
Student other = (Student) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}