java HashSet應用

來源:互聯網
上載者:User

        在使用HashSet時,應注意:一、自己的類有屬性,就應當重寫方法equals和hashCode;二、寫方法時要遵守的原則,兩個類equals返回true時,hashCode一定相等(考慮一下雜湊表的衝突就可以理解);三、在使用時不得隨意修改HashSet中的值,否定將會導致結果不準確性。

import java.util.*;class R{public int count;public R (int count){this.count = count;}public String toString(){return "R(count " + count + " )";}public boolean equals(Object obj){if(obj instanceof R){R r = (R)obj;if( r.count == this.count)return true;}return false;}public int hashCode(){return this.count;}}public class TestHashSet{public static void main(String[] args){HashSet hs = new HashSet();hs.add(new R(5));hs.add(new R(-3));hs.add(new R(9));hs.add(new R(-2));System.out.println(hs);Iterator it = hs.iterator();R first = (R)it.next();first.count = -3;//直接改變,最好先刪除再插入System.out.println(hs);hs.remove(new R(-3));//只尋找到了原先的-3System.out.println(hs);System.out.println("has -3 " + hs.contains(new R(-3)));//falseSystem.out.println("has -5 " + hs.contains(new R(-5)));//false}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.