标签:package ping pack rem tor nta his eset this
TreeSet是SortedSet接口的实现类,该集合可以保证元素处于排序状态,并且它支持自然排序和自定义排序,默认情况下采取自然排序。
它实现的方式是比较元素之间的大小关系,如下:
注意进行比较的对象,他们的数据类型应该相同
package peterxiazhe; import java.util.Comparator; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class test4 { public static void main(String[] args) { Set<Integer> set = new TreeSet<Integer>(); //自然排序 set.add(2); set.add(3); set.add(6); set.add(10); System.out.println(set); set.remove(6); System.out.println(set); System.out.println(set.contains(10)); for(Integer obj: set) { System.out.println(obj); } set.add(15); Iterator<Integer> it = set.iterator(); while(it.hasNext()) { System.out.println(it.next()); } Person p1 = new Person(21, "Xia Chen"); Person p2 = new Person(11, "Li Ying"); Person p3 = new Person(9, "Zhou Ping"); Person p4 = new Person(31, "Xu Rui"); Person p5 = new Person(21, "Li fan"); Set<Person> set = new TreeSet<Person>(new Person()); set.add(p1); set.add(p2); set.add(p3); set.add(p4); set.add(p5); System.out.println(set.size()); for(Person p: set) { System.out.println(p.name + " " + p.age); } } } class Person implements Comparator<Person>{//将Person存到TreeSet,并且按照age排序 public int age; public String name; public Person() {} public Person(int age, String name) { this.age = age; this.name = name; } //自定义排序 public int compare(Person x1, Person x2) { if (x1.age >= x2.age) { return 1; }else{ return -1; } } }
标签:package ping pack rem tor nta his eset this
原文地址:https://www.cnblogs.com/xiazhenbin/p/13681694.html