/*Set : 无序,不可以重复元素|--HashSet:数据结构是哈希表,线程是非同步的保证元素唯一性原理: 判断元素的HashCode值是否相同如果相同,还会继续判断元素的equals方法是否为True|TreeSet: 可以对集合中的元素进行排序底层数据结构是二叉树保证元素唯一性的依据是compareTo方法TreeSet排序的第一种方式:让元素自身具备比较性元素需要实现Comparable接口,覆盖compareTo方法这种方式也称为元素的自然顺序,或者叫做默认顺序
*/import java.util.*;class Student implements Comparable//该接口强制让学生具备比较性
{private String name;private int age;Student(String name, int age){this.name = name;this.age = age;}public String getName(){return name;}public int getAge(){return age;}public int compareTo(Object obj)//覆盖父类中的函数{if( !(obj instanceof Student))throw new RuntimeException("不是学生对象!");Student stu = (Student)obj;if(this.age < stu.age)return -1;if(stu.age == this.age)return this.name.compareTo(stu.name);//当主要条件相同时 ,也要判断次要条件return 1;}}class TreeSetDemo
{public static void main(String []args){TreeSet ts = new TreeSet();ts.add(new Student("NUM3",33));ts.add(new Student("NUM2",22));ts.add(new Student("NUM1",11));ts.add(new Student("NUM4",44));// ts.add("aab");
// ts.add("aaa");
// ts.add("aaba");
// ts.add("cdb");
// ts.add("Dad");//大写的D 的ASCLL 码值比a 小
// //TreeSet 是按照元素的ASCLL 大小进行排序Iterator it = ts.iterator();while( it.hasNext()){Student s = (Student)it.next();sop( s.getName() + " "+ s.getAge());}}public static void sop(Object obj){System.out.println(obj);}}
转载于:https://www.cnblogs.com/dengshiwei/p/4258524.html