Sobes.tech
Junior

Mis on Set Java's?

sobes.tech AI

Vastus AI-lt

Set in Java is a collection of unique elements that does not guarantee the order of storage.

Main features:

  • Uniqueness: Cannot contain duplicates. If you try to add an existing element, the operation will be ignored (depending on implementation).
  • Lack of indexing: Elements are not accessible by index.
  • Interface: Part of the Java Collections Framework and extends the Collection interface.

Most commonly used implementations:

  • HashSet: The fastest implementation, based on a hash table. Does not guarantee the order of elements.
  • LinkedHashSet: Maintains insertion order, using a linked list in addition to the hash table.
  • TreeSet: Stores elements in sorted order (natural or by a specified comparator), based on a red-black tree.

Example of using HashSet:

// Creating a HashSet
Set<String> uniqueNames = new HashSet<>();

// Adding elements
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // This element will be ignored
uniqueNames.add("Charlie");

// Checking if it contains an element
boolean containsBob = uniqueNames.contains("Bob"); // true

// Iterating over elements (order not guaranteed)
for (String name : uniqueNames) {
    System.out.println(name);
}

// Size of the Set
int size = uniqueNames.size(); // 3