Java Collection Framwork中的equals方法

來源:互聯網
上載者:User

剛剛看到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是不一樣的)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.