Set的特點:
Set無法記住元素添加的順序,不允許包含重複的元素。
Set判斷兩個對象是否相等用equals方法。
常用子類:
HashSet 散列存放,查詢速度快
TreeSet 有序存放
import java.util.HashSet;import java.util.Set;public class SetDemo {public static void main(String[] args) {Set set = new HashSet();set.add("well");//HashSet不允許添加重複元素set.add("well");System.out.println(set);//[well]set.add(null);//HashSet最多隻能添加一個nullset.add(null);System.out.println(set);//[null, well]//清空元素set.clear();System.out.println(set);}}
TreeSet使用元素的自然順序進行排序,或者根據建立Set時提供的Compatator進行排序;參與排序的元素必須是同一類型的。
自然排序:
TreeSet會調用元素的compareTo(Object o)方法來比較元素之間的大小關係,然後將集合裡的元素按升序排列。此時需要排序元素的類必須實現Comparable介面,並覆寫其compareTo方法。
import java.util.Set;import java.util.TreeSet;/* * 要求根據年齡來排序,升序 * */class Person implements Comparable{private String name;private Integer age;Person(String name, Integer age) {super();this.name = name;this.age = age;}/* * 完成要求排序,需實現Comparable介面,並覆寫compareTo方法 */public int compareTo(Object o) {if(o instanceof Person){Person p = (Person)o;return this.age.compareTo(p.age);}return 0;}@Overridepublic String toString() {return this.name + "-" + this.age;}}public class TreeSetDemo {public static void main(String[] args) {Set set = new TreeSet();set.add(new Person("well",21));set.add(new Person("tom",20));set.add(new Person("Lily",22));System.out.println(set);//[tom-20, well-21, Lily-22]}}
定製排序:
若想按照自己的要求進行排序,則可以使用Comparator介面,該介面包含compare(o1,o2)方法,用於比較兩個對象的大小。
import java.util.Comparator;import java.util.Set;import java.util.TreeSet;/* * TreeSet預設是升序排列 * 現在要求:根據年齡來排序,降序排列 */class Student{private String name;private Integer age;Student(String name, Integer age) {super();this.name = name;this.age = age;}public String getName() {return name;}public Integer getAge() {return age;}public String toString() {return this.name +"-"+ this.age;}}/** * 定製自己的定序:降序排列 * 實現Comparator介面,覆寫compare方法 * 根據第一個參數小於、等於或大於第二個參數分別返回負整數、零或正整數。 */class MyComparator implements Comparator{@Overridepublic int compare(Object o1, Object o2) {Student s1 = (Student)o1;Student s2 = (Student)o2;if(s1.getAge()>s2.getAge())return -1;else if(s1.getAge() < s2.getAge())return 1;return 0;}}public class ComparatorDemo {public static void main(String[] args) {/* * TreeSet(Comparator<? super E> comparator) * 構造一個新的空 TreeSet,它根據指定比較子進行排序。 */Set set = new TreeSet(new Comparator() {//使用匿名內部類,這裡寫比較規則@Overridepublic int compare(Object o1, Object o2) {Student s1 = (Student)o1;Student s2 = (Student)o2;if(s1.getAge()>s2.getAge())return -1;else if(s1.getAge() < s2.getAge())return 1;return 0;}});set.add(new Student("Tom",20));set.add(new Student("Lily",18));set.add(new Student("Well",25));System.out.println(set);}}