举例说明:public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<>();
ts.add("a");
ts.add("c");
ts.add("t");
ts.add("b");
ts.add("e");
ts.add("o");
ts.add("f");
System.out.println(ts); //[a, b, c, e, f, o, t],自动排序,因为String中实现了Comparable接口,按字典排序
for (String string : ts) { //增强for遍历
System.out.print(string + " ");
}
System.out.println();
TreeSet<Student> ts2 = new TreeSet<>(new Comparator<Student>() { //传入比较器comparator
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
return num == 0? s1.getName().compareTo(s2.getName()) : num;
}
});
ts2.add(new Student("张三", 23));
ts2.add(new Student("周期", 24));
ts2.add(new Student("王武", 25));
ts2.add(new Student("赵六", 26));
ts2.add(new Student("李四", 24));
System.out.println(ts2);
Iterator<Student> it = ts2.iterator(); //迭代器遍历
while (it.hasNext()) {
System.out.println(it.next());
}
TreeSet<Student> ts3 = new TreeSet<>(); //Student类实现了comparable接口,按照定义好的compareTo方法排序
ts3.add(new Student("张三", 23));
ts3.add(new Student("周期", 24));
ts3.add(new Student("王武", 25));
ts3.add(new Student("赵六", 26));
ts3.add(new Student("李四", 24));
System.out.println(ts3);
for (Student student : ts3) { //增强for遍历
System.out.println(student);
}
}
}
不好意思,刚有事,耽误了会.... |