zoukankan      html  css  js  c++  java
  • Java HashSet集合的子类LinkedHashSet集合

    说明

    HashSet保证元素的唯一性,可是元素存放进去是没有顺序的。

    在HashSet下面有一个子类java.util.LinkedHashSet,它是 链表 + 哈希表(数组+链表 或者 数组+红黑树)组合的一个数据结构。

    即相对HashSet而言,多了一个链表结构。多了的那条链表,用来记录元素的存储顺序,保证元素有序

    举例

    HashSet集合例子1

    import java.util.HashSet;
    
    public class DemoLinkedHashSet {
        public static void main(String[] args) {
            HashSet<String> hashSet = new HashSet<>();
    
            hashSet.add("https");
            hashSet.add("www");
            hashSet.add("cnblogs");
            hashSet.add("com");
            System.out.println(hashSet);
        }
    }
    输出结果:
    [com, cnblogs, www, https]

    HashSet集合例子2

    将例子1中添加元素的顺序调换一下

    import java.util.HashSet;
    
    public class DemoLinkedHashSet {
        public static void main(String[] args) {
            HashSet<String> hashSet = new HashSet<>();
    
            hashSet.add("cnblogs");
            hashSet.add("com");
            hashSet.add("https");
            hashSet.add("www");
            System.out.println(hashSet);
        }
    }
    输出结果:
    [com, cnblogs, www, https]

    可以看出,HashSet集合存储的元素是无序的。

    LinkedHashSet集合例子1

    import java.util.LinkedHashSet;
    
    public class DemoLinkedHashSet {
        public static void main(String[] args) {
            LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
    
            linkedHashSet.add("https");
            linkedHashSet.add("www");
            linkedHashSet.add("cnblogs");
            linkedHashSet.add("com");
            System.out.println(linkedHashSet);
        }
    }
    输出结果:
    [https, www, cnblogs, com]

    LinkedHashSet集合例子2

    将例子1中添加元素的顺序调换一下

    import java.util.LinkedHashSet;
    
    public class DemoLinkedHashSet02 {
        public static void main(String[] args) {
            LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
    
            linkedHashSet.add("cnblogs");
            linkedHashSet.add("com");
            linkedHashSet.add("https");
            linkedHashSet.add("www");
            System.out.println(linkedHashSet);
        }
    }
    输出结果:
    [cnblogs, com, https, www]

    可以看出,LinkedHashSet集合存储的元素是有序的。

  • 相关阅读:
    [leetcode] Rotate Image
    [leetcode] Jump Game II
    [leetcode] Permutations II
    [leetcode] Permutations
    [leetcode] Wildcard Matching
    [leetcode] Multiply Strings
    [leetcode] Trapping Rain Water
    [leetcode] First Missing Positive
    [leetcode] Combination Sum II
    [leetcode] Combination Sum
  • 原文地址:https://www.cnblogs.com/liyihua/p/12194806.html
Copyright © 2011-2022 走看看