Java集合框架学习(四) LinkedHashSet详解

LinkedHashSet介绍


前面我们介绍了HashSet和TreeSet。

LinkedHashSet也是Set接口的一个实现类,同时还继承了HashSet

public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, Serializable

它和HashSet,TreeSet类似,以下是其特点:

1. LinkedHashSet是具有可预知迭代顺序的Set接口的哈希表和链接列表实现。

此实现与HashSet的不同之处在于,后者维护着一个运行于所有条目的双重链接列表。

此链接列表定义了迭代顺序,该迭代顺序可为插入顺序或是访问顺序。

2. LinkedHashSet底层使用LinkedHashMap来保存所有元素,它继承与HashSet,其所有的方法操作上又与HashSet相同。

3. LinkedHashSet也是非线程安全的。

4. 允许有null元素。


LinkedHashSet例子


package com.dylan.collection;

import java.util.LinkedHashSet;

/**
 * @author xusucheng
 * @create 2018-01-27
 **/
public class LinkedHashSetExample {
    public static void main(String args[]) {
        // LinkedHashSet of String Type
        LinkedHashSet<String> lhset = new LinkedHashSet<String>();

        // Adding elements to the LinkedHashSet
        lhset.add("Z");
        lhset.add("PQ");
        lhset.add("N");
        lhset.add("O");
        lhset.add("KK");
        lhset.add("FGH");
        System.out.println(lhset);

        // LinkedHashSet of Integer Type
        LinkedHashSet<Integer> lhset2 = new LinkedHashSet<Integer>();

        // Adding elements
        lhset2.add(99);
        lhset2.add(7);
        lhset2.add(0);
        lhset2.add(67);
        lhset2.add(89);
        lhset2.add(66);
        System.out.println(lhset2);
    }
}


输出:

[Z, PQ, N, O, KK, FGH]
[99, 7, 0, 67, 89, 66]








posted @ 2018-01-27 12:31  一锤子技术员  阅读(1)  评论(0编辑  收藏  举报  来源