Senior
What collection should be used to store the history of visited pages without duplicates while preserving order?
sobes.tech AI
Answer from AI
To store the history of visited pages without duplicates while preserving order in Java, it is best to use the LinkedHashSet collection.
- LinkedHashSet is an implementation of the Set interface that maintains the insertion order of elements.
- It does not allow duplicates, meaning if a page has already been added, re-adding it will not change the collection.
Example:
import java.util.LinkedHashSet;
LinkedHashSet<String> history = new LinkedHashSet<>();
// Adding pages
history.add("page1.html");
history.add("page2.html");
history.add("page1.html"); // will not be added again
// Iteration preserves the insertion order
for (String page : history) {
System.out.println(page);
}
The output will be:
page1.html
page2.html
Thus, LinkedHashSet is ideal for storing unique elements while maintaining order.