從頭認識java-15.3 使用HashSet須要注意的地方

來源:互聯網
上載者:User

標籤:put   code   hashcode   his   type   const   access   int   rgb   

這一章節我們來討論一下使用Set的各種實現須要注意的地方。

Set介面的經常使用實作類別有:HashSet。TreeSet,LinkedHashSet


1.HashSet

大家對於HashSet的印象都是它能夠去除反覆的元素,每個元素都是唯一的,可是這裡面有一個前提。就是必須重寫equals和hashcode方法。

大家的印象大都是以下這個:

package com.ray.ch15;import java.util.HashSet;public class Test {public static void main(String[] args) {HashSet<Integer> set = new HashSet<Integer>();set.add(1);set.add(2);set.add(3);for (int i = 0; i < 10; i++) {set.add(i);}System.out.println(set);}}
輸出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

事實上當中的原因是,set裡面的equals和hashcode方法都繼承了Object裡面的。而Object裡面的這兩個方法剛好能夠比較easy的對照java的基礎類型,甚至java裡面大部分的類型。由於大部分類型都已經重寫了equals和hashcode方法。

那麼,我們以下自己定義一下自己的類型看看:

package com.ray.ch15;import java.lang.reflect.InvocationTargetException;import java.util.HashSet;import java.util.Set;public class Test<T> {public static <T> Set<T> fill(Set<T> set, Class<T> type)throws InstantiationException, IllegalAccessException,IllegalArgumentException, SecurityException,InvocationTargetException, NoSuchMethodException {for (int i = 0; i < 10; i++) {set.add(type.getConstructor(int.class).newInstance(i));}return set;}public static <T> void test(Set<T> set, Class<T> type)throws IllegalArgumentException, SecurityException,InstantiationException, IllegalAccessException,InvocationTargetException, NoSuchMethodException {fill(set, type);fill(set, type);fill(set, type);System.out.println(set);}public static void main(String[] args) throws IllegalArgumentException,SecurityException, InstantiationException, IllegalAccessException,InvocationTargetException, NoSuchMethodException {test(new HashSet<SetType>(), SetType.class);test(new HashSet<HashType>(), HashType.class);}}class SetType {private int id = 0;public int getId() {return id;}public void setId(int id) {this.id = id;}public SetType(int i) {id = i;}@Overridepublic String toString() {return id + "";}@Overridepublic boolean equals(Object obj) {return obj instanceof SetType && (id == ((SetType) obj).id);}}class HashType extends SetType {public HashType(int i) {super(i);}@Overridepublic int hashCode() {return getId();}}

輸出:

[6, 6, 3, 4, 9, 5, 2, 9, 1, 7, 5, 4, 1, 2, 9, 3, 7, 8, 8, 0, 2, 0, 4, 6, 7, 5, 0, 1, 3, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

解釋一下上面的代碼:

(1)fill方法:通過泛型和反射。往傳進來的set裡面加入資料

(2)test方法:我們通過多次的往set裡面填充資料,看看set是否去重

(3)SetType:原始類型,僅僅是簡單實現了equals方法和toString方法,toString這裡通過輸出id來表示對象

(4)HashType:繼承SetType,再實現了hashCode方法


注意點:

(1)從輸出我們能夠看見。在main的第一個test方法,它的輸出是許多的對象id,並且裡面出現了許多的反覆。這是由於我們沒有重寫hashCode方法,在Object的hashCode方法裡面。每個對象返回的hashcode都不一樣。jvm認定都是不同的對象,因此我們加入多少對象進去,就會顯示多少對象

(2)接著上面的解釋,以下的HashType重寫了hashCode方法。以id為標準,從上面的代碼我們能夠看見,id很可能反覆,因此jvm就會去重。

我們能夠翻開HashSet的源碼,看看add方法:

private transient HashMap<E,Object> map;public boolean add(E e) {return map.put(e, PRESENT)==null;    }
對象是放到map裡面,我們在翻開map的put方法:

public V put(K key, V value) {        if (key == null)            return putForNullKey(value);        int hash = hash(key.hashCode());        int i = indexFor(hash, table.length);        for (Entry<K,V> e = table[i]; e != null; e = e.next) {            Object k;            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {                V oldValue = e.value;                e.value = value;                e.recordAccess(this);                return oldValue;            }        }        modCount++;        addEntry(hash, key, value, i);        return null;    }

它裡面是對照了hash值的,因此HashSet想實現去重,必須重寫equals和hashcode方法。

(3)由於上面產生的值比較少,因此排序的特殊性沒有表露出來。當我們添加建立的對象時。排序就會依照一定的順序排列,而不是依照我們想象的順序。

關於這樣的排序,我們後面的章節會說到。

以下是範例代碼:

package com.ray.ch15;import java.lang.reflect.InvocationTargetException;import java.util.HashSet;import java.util.Set;public class Test<T> {public static <T> Set<T> fill(Set<T> set, Class<T> type)throws InstantiationException, IllegalAccessException,IllegalArgumentException, SecurityException,InvocationTargetException, NoSuchMethodException {for (int i = 0; i < 20; i++) {set.add(type.getConstructor(int.class).newInstance(i));}return set;}public static <T> void test(Set<T> set, Class<T> type)throws IllegalArgumentException, SecurityException,InstantiationException, IllegalAccessException,InvocationTargetException, NoSuchMethodException {fill(set, type);fill(set, type);fill(set, type);System.out.println(set);}public static void main(String[] args) throws IllegalArgumentException,SecurityException, InstantiationException, IllegalAccessException,InvocationTargetException, NoSuchMethodException {test(new HashSet<HashType>(), HashType.class);}}class SetType {private int id = 0;public int getId() {return id;}public void setId(int id) {this.id = id;}public SetType(int i) {id = i;}@Overridepublic String toString() {return id + "";}@Overridepublic boolean equals(Object obj) {return obj instanceof SetType && (id == ((SetType) obj).id);}}class HashType extends SetType {public HashType(int i) {super(i);}@Overridepublic int hashCode() {return getId();}}

輸出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18]


總結:這一章節主要講述了使用HashSet須要注意的地方。


這一章節就到這裡,謝謝。

-----------------------------------

檔案夾









從頭認識java-15.3 使用HashSet須要注意的地方

聯繫我們

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