package com.wzy.list;import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;class Student1 implements Comparable{
private Integer id;
private String name; public Student1(String name,Integer id) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "name:"+name+"; id:"+id;
}
@Override
public int compareTo(Object o) {
if(this.id > ((Student1)o).id) {
return ;
}else if(this.id < ((Student1)o).id) {
return -;
}else{
return this.name.compareTo(((Student1)o).name);
} }
}class Student2{
private Integer id;
private String name; public Student2(String name,Integer id) {
this.id = id;
this.name = name;
} @Override
public int hashCode() {
final int prime = ;
int result = ;
result = prime * result + ((id == null) ? : id.hashCode());
result = prime * result + ((name == null) ? : 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;
Student2 other = (Student2) 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;
} @Override
public String toString() {
return "Student2 [id=" + id + ", name=" + name + "]";
} }
public class Test02 {
public static void main(String[] args) {
/**
* TreeSet和HashSet存入对象时,不会自动去重操作
*
* TreeSet去掉重复对象,基于Comparable接口实现
* HashSet去掉重复对象,基于equals和hashCode实现
* TreeSet可以对象排序,hashSet不可以
*
* 如果存入的不是new出来的对象,
* 而是String或int类型,可以直接使用,不必实现上述操作
* **/ //TreeSet存入对象实例
Set<Student1> stu1 = new TreeSet<Student1>();
stu1.add(new Student1("aa",));
stu1.add(new Student1("bb",));//id重复
stu1.add(new Student1("dd",));
stu1.add(new Student1("cc",));
stu1.add(new Student1("aa",));//对象重复
Iterator s = stu1.iterator();
while(s.hasNext()) {
System.out.println(s.next());
} //HashSet存入对象实例
Set<Student2> stu2 = new HashSet<Student2>();
stu2.add(new Student2("aa",));
stu2.add(new Student2("bb",));
stu2.add(new Student2("cc",));
stu2.add(new Student2("dd",));
stu2.add(new Student2("ee",));
stu2.add(new Student2("aa",)); Iterator i = stu2.iterator();
while(i.hasNext()) {
System.out.println(i.next());
} //TreeSet存入普通字符串
Set set1 = new TreeSet();
set1.add("a");
set1.add("aa");
set1.add("d");
set1.add("b");
set1.add("c");
//[a, aa, b, c, d] TreeSet已经自动排序好了
System.out.println(set1); //HashSet存入普通字符串
Set set2 = new HashSet();
set2.add("a");
set2.add("aa");
set2.add("d");
set2.add("c");
set2.add("b");
//[aa, a, b, c, d] HashSet不会排序
System.out.println(set2);
}
}