Java HashSet
Java HashSet
HashSet 是一个项目集合,其中每个项目都是唯一的,它位于 java.util
包中。
示例
创建一个名为 cars 的 HashSet
对象,用于存储字符串。
import java.util.HashSet; // Import the HashSet class
HashSet<String> cars = new HashSet<String>();
Add Items
HashSet
类有许多有用的方法。例如,要向其中添加项目,请使用 add()
方法。
示例
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW");
cars.add("Mazda");
System.out.println(cars);
}
}
注意:在上面的示例中,尽管 BMW 被添加了两次,但它在集合中只出现一次,因为集合中的每个项目都必须是唯一的。
检查项目是否存在
要检查 HashSet 中是否存在某个项目,请使用 contains()
方法。
Remove an Item
要删除项目,请使用 remove()
方法。
要删除所有项目,请使用 clear()
方法。
HashSet 大小
要查找有多少个项目,请使用 size
方法。
遍历 HashSet
使用 for-each 循环遍历 HashSet
中的项目。
Other Types
HashSet 中的项目实际上是对象。在上面的示例中,我们创建了类型为“String”的项目(对象)。请记住,Java 中的 String 是一个对象(而不是原始类型)。要使用其他类型,例如 int,您必须指定一个等效的包装类:Integer
。对于其他原始类型,请使用:boolean 的 Boolean
,char 的 Character
,double 的 Double
,等等。
示例
使用存储 Integer
对象的 HashSet
。
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// Create a HashSet object called numbers
HashSet<Integer> numbers = new HashSet<Integer>();
// Add values to the set
numbers.add(4);
numbers.add(7);
numbers.add(8);
// Show which numbers between 1 and 10 are in the set
for(int i = 1; i <= 10; i++) {
if(numbers.contains(i)) {
System.out.println(i + " was found in the set.");
} else {
System.out.println(i + " was not found in the set.");
}
}
}
}