剛剛看到Set的equals方法,從Collection到Set,沒有多了什麼別的方法,不過多了些限制,比如Set的中的元素不能重複(不會有e1和e2都屬於一個Set,且e1.equals(e2)這種情況),然後就是在equals方法上的限制,兩個Set equals若且唯若它們有著相同的elements(就是對於任意set1中的e1,在set2中一定存在一個e2,e1.equals(e2)返回true,同時對於Set2中的任意一個e2,Set1中存在e1,e2.equals(e1)返回true,這裡我不考慮有些Set允許加入null那種情況),一個例子如下:
import java.util.Arrays;import java.util.Collection;import java.util.HashSet;import java.util.LinkedHashSet;import java.util.TreeSet;public class Test {public static void main(String[] args) {String[] sa = {"abc", "spam", "ham", "egg", "dog"};Collection<String> cs = Arrays.asList(sa);HashSet<String> set1 = new HashSet<String>(cs);TreeSet<String> set2 = new TreeSet<String>(cs);LinkedHashSet<String> set3 = new LinkedHashSet<String>(cs);System.out.println(set1.equals(set2));System.out.println(set1.equals(set3));//set1.add(null);//set2.add(null);//set3.add(null);System.out.println(set2.equals(set3));}}
有些Set允許至多有一個null(例如HashSet和LinkedHashSet),有些不允許有null(例如TreeSet),這裡就不考慮了。(有null和沒有null是不一樣的)