Java 简明教程

Java LinkedHashSet Class

Introduction

Java LinkedHashSet 类是一个哈希表和 Set 接口的链表实现,具有可预测的迭代顺序。以下是有关 LinkedHashSet 的重要要点:

The Java LinkedHashSet class is a Hash table and Linked list implementation of the Set interface, with predictable iteration order.Following are the important points about LinkedHashSet −

  1. This class provides all of the optional Set operations, and permits null elements.

Class declaration

以下是 java.util.LinkedHashSet 类的声明:

Following is the declaration for java.util.LinkedHashSet class −

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

Parameters

以下是 java.util.LinkedHashSet 类的参数:

Following is the parameter for java.util.LinkedHashSet class −

E − 这是该集合维护的元素类型。

E − This is the type of elements maintained by this set.

Class constructors

Class methods

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.util.HashSet

  2. java.util.AbstractSet

  3. java.util.AbstractCollection

  4. java.util.Object

  5. java.util.Set

Getting a Spliterator() to Iterate Entries of LinkedHashSet Example

以下示例显示 Java LinkedHashSet spliterator() 方法在迭代 LinkedHashSet 条目的用法。我们已经创建了一个 Integer 的 LinkedHashSet 对象。然后使用 add() 方法添加少量条目,然后使用 spliterator() 方法获取一个 spliterator,并通过遍历 spliterator 来打印每个值。

The following example shows the usage of Java LinkedHashSet spliterator() method to iterate entries of the LinkedHashSet. We’ve created a LinkedHashSet object of Integer. Then few entries are added using add() method and then an spliterator is retrieved using spliterator() method and each value is printed by iterating through the spliterator.

package com.tutorialspoint;

import java.util.LinkedHashSet;
import java.util.Spliterator;

public class LinkedHashSetDemo {
   public static void main(String args[]) {

      // create hash set
      LinkedHashSet <Integer> newset = new LinkedHashSet <>();

      // populate hash set
      newset.add(1);
      newset.add(2);
      newset.add(3);

      // create an spliterator
      Spliterator<Integer> spliterator = newset.spliterator();

      // check values
      spliterator.forEachRemaining(v -> System.out.println(v));
   }
}

让我们编译并运行以上的程序,这会生成以下结果:

Let us compile and run the above program, this will produce the following result.

1
2
3