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.");
}
}
}
}