Linked Hashset In Java
LinkedHashSet in Java
LinkedHashSet is a part of the Java Collections Framework and is an implementation of the Set interface. It combines the features of both HashSet and LinkedList. LinkedHashSet maintains a predictable iteration order, which is the order in which elements were inserted into the set. Like HashSet, it does not allow duplicate elements and provides constant-time performance for basic operations.
Declaration and Initialization
To use a LinkedHashSet in Java, you need to import the java.util.LinkedHashSet
package. Here's an example of declaring and initializing a LinkedHashSet:
import java.util.LinkedHashSet;
public class Example {
public static void main(String[] args) {
LinkedHashSet<String> cities = new LinkedHashSet<>();
// Adding elements to the LinkedHashSet
cities.add("New York1");
cities.add("London1");
cities.add("Tokyo1");
// No duplicate elements allowed
cities.add("New York1"); // This won't be added
// Accessing elements
for (String city : cities) {
System.out.println(city);
}
// Removing elements
cities.remove("London1");
// Checking if an element exists
boolean exists = cities.contains("Tokyo1");
System.out.println("Tokyo1 exists in the set: " + exists)
}
}
Common LinkedHashSet Operations
Here are some commonly used operations with LinkedHashSets:
add(element)
: Adds an element to the LinkedHashSet.remove(element)
: Removes an element from the LinkedHashSet.contains(element)
: Checks if the LinkedHashSet contains a specific element.size()
: Returns the number of elements in the LinkedHashSet.isEmpty()
: Checks if the LinkedHashSet is empty.clear()
: Removes all elements from the LinkedHashSet.
LinkedHashSet is an excellent choice when the requirement is to maintain a unique set of elements with a predictable order of insertion. It provides efficient and predictable performance for most set operations and is widely used in various Java applications.