public class TestSet {
public static void main(String[] args) {
Set set = new HashSet();
Teacher t1 = new Teacher("haitao",50);
Teacher t2 = new Teacher("xubin",1000);
Teacher t3 = new Teacher("wangwei",80000);
Teacher t4 = new Teacher("haitao",50);
set.add(t1);
set.add(t2);
set.add(t3);
set.add(t4);
Set treeset = new TreeSet(set);
treeset.addAll(set);
// t4.setName("hai"); 导致内存泄露
// set.remove(t4);
Iterator it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
public class Teacher implements Comparable{//Comparable接口用于排序
private String name;
private int salary;
public Teacher(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public String toString() {
return this.name+":"+this.salary;
}
public int compareTo(Object o) {
if(o instanceof Teacher){
Teacher teacher = (Teacher)o;
//return this.getSalary()-teacher.getSalary();
return this.getName().compareTo(teacher.getName());
}
return 0;
}
@Override
public boolean equals(Object obj) {
//System.out.println("in equals...");
if(this == obj){
return true;
}
if(obj == null){
return false;
}
if(obj instanceof Teacher){
Teacher t1 = (Teacher) obj;
return t1.getName().equals(this.getName());
}
return false;
}
public int hashCode() {
//System.out.println("in hashCode...");
return name.hashCode();
}
}