Java 简明教程
Java HashSet Class
Introduction
Java HashSet 类实现了 Set 接口,由哈希表提供支持。以下是对 HashSet 的重要说明:
The Java HashSet class implements the Set interface, backed by a hash table.Following are the important points about HashSet −
-
This class makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
-
This class permits the null element.
Class declaration
以下是对 java.util.HashSet 类的声明:
Following is the declaration for java.util.HashSet class −
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable
Parameters
以下是对 java.util.HashSet 类的参数:
Following is the parameter for java.util.HashSet class −
E − 这是该集合维护的元素类型。
E − This is the type of elements maintained by this set.
Methods inherited
此类从以下类中继承方法:
This class inherits methods from the following classes −
-
java.util.AbstractSet
-
java.util.AbstractCollection
-
java.util.Object
-
java.util.Set
Adding element to a HashSet Example
以下示例显示了 Java HashSet add() 方法的用法,以向 HashSet 中添加条目。我们创建了一个 Integer 的 HashSet 对象。然后使用 add() 方法添加了一些条目,然后打印集合。
The following example shows the usage of Java HashSet add() method to add entries to the HashSet. We’ve created a HashSet object of Integer. Then few entries are added using add() method and then set is printed.
package com.tutorialspoint;
import java.util.HashSet;
public class HashSetDemo {
public static void main(String args[]) {
// create hash set
HashSet <Integer> newset = new HashSet <>();
// populate hash set
newset.add(1);
newset.add(2);
newset.add(3);
// checking elements in hash set
System.out.println("Hash set values: "+ newset);
}
}