第四章 java中的LinkedHashSet


在这篇文章中,我们将了解 Java 中的 LinkedHashSet。LinkedHashSet 与 HashSet 相同,只是它维护插入顺序。

关于 LinkedHashSet 的几点

  1. LinkedHashSet 实现了 Set 接口并扩展了 HashSet 类。
  2. LinkedHashSet 维护插入顺序,因此当您能够像 ArrayList 一样按照插入顺序访问元素时。

例子:

LinkedHashSetMain.java

package org.arpit.java2blog;

import java.util.LinkedHashSet;

public class LinkedHashSetMain {

 public static void main(String args[])
 {
 // LinkedHashSet with Country
 // LinkedHashSet maintains insertion order  
  LinkedHashSet<String> countryHashSet=new LinkedHashSet<String>();
  countryHashSet.add("India");
  countryHashSet.add("Japan");
  countryHashSet.add("France");
  countryHashSet.add("Russia");
  countryHashSet.add("India");
  countryHashSet.add("France");
  countryHashSet.add("United Kingdom");

  System.out.println("-----------------------------");

  System.out.println("Iterating LinkedHashSet");
  System.out.println("-----------------------------");
  for (String country:countryHashSet) {
   System.out.println(country);

  }
  System.out.println("-----------------------------");
}

}

当你运行上面的程序时,你会得到下面的输出:

-----------------------------
Iterating LinkedHashSet
-----------------------------
India
Japan
France
Russia
United Kingdom
-----------------------------


原文链接:https://codingdict.com/