Set接口 类似一个大口袋,可以放很多东西,且不考虑摆放顺序。set中不能包含重复的对象
Set接口
HashSet散列集合 TreeSet树集合
高效快速 存放有序
TreeSet代码演示
Person类
public class Person implements Comparable{
int id;
int age;
String name;
public Person(int id, int age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", age=" + age + ", name=" + name + "]";
}
@Override
public int compareTo(Object o) {
Person p;
if (o instanceof Person ) {
p = (Person)o;
}else {
return -1;//-1代表传入的参数比我本身要小
}
int diff = this.id -p.id; //通过id进行排序,也可以通过年龄排序 只需要把id改成age
if (diff!=0) {
diff = diff/Math.abs(diff);//差值除以本身绝对值,可以得到+1或-1的值。
}
return diff;
}
}
Demo类
public static void main(String[] args) {
Set set = new TreeSet();
Person p1 = new Person(1,18,"小明");
Person p2 = new Person(2,5,"小何");
Person p3 = new Person(3,20,"小红");
set.add(p1);
set.add(p2);
set.add(p3);//重复的元素不会被添加到集合中
// set.add(null);//set集合中不能添加null值
System.out.println(set.size());
Iterator it = set.iterator();//创建一个迭代器
while (it.hasNext()) {
System.out.println(it.next());
}
}