從頭認識java-15.5 使用LinkedHashSet需要注意的地方

來源:互聯網
上載者:User

從頭認識java-15.5 使用LinkedHashSet需要注意的地方

再接著上一個章節,我們來聊一下使用LinkedHashSet需要注意的地方。

LinkedHashSet特點:

(1)元素是有順序的

(2)元素是不重複的

(3)底層資料結構是按照鏈表的結構儲存的

(4)需要重新hashcode和equals方法

例子:(我們再次修改上一章節的代碼)

package com.ray.ch15;import java.lang.reflect.InvocationTargetException;import java.util.LinkedHashSet;import java.util.Set;public class Test {public static  Set fill(Set set, Class 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  void test(Set set, Class 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 LinkedHashSet(), TreeType.class);test(new LinkedHashSet(), SetType.class);test(new LinkedHashSet(), 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();}}class TreeType extends HashType implements Comparable {public TreeType(int i) {super(i);}@Overridepublic int compareTo(TreeType o) {if (o.getId() > getId()) {// 排序return -1;} else {if (o.getId() == getId()) {// 去重return 0;} else {return 1;}}}}

輸出:

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

注意:在TreeType裡面的Comparable介面是沒什麼用的。

總結:我們這一章節簡單展示了使用LinkedHashSet需要注意的地方。

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

聯繫我們

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