Java: HashSet

A HashSet is a collection of items where every item is unique, and it is found in the java.util package:

import java.util.HashSet; // Import the HashSet class

HashSet<String> cars = new HashSet<String>();

Add Items

// 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);
  }
}

// Outputs:
[Volvo, Mazda, Ford, BMW]

Check If an Item Exists

cars.contains("Mazda");

Remove an Item

cars.remove("Volvo");

To remove all items, use the clear() method:

cars.clear();

HashSet Size

cars.size();

Loop Through a HashSet

for (String i : cars) {
  System.out.println(i);
}

// Outputs:
Volvo
Mazda
Ford
BMW

 

posted @ 2022-11-27 19:32  小白冲冲  阅读(46)  评论(0)    收藏  举报