TreeSet, HashSet, LinkedHashSet in Java

Difference between TreeSet and HashSet

TreeSet provides an ordered storage of elements in a red-black tree. The complexity of performing basic operations is no worse than O(log(N)) (Logarithmic time).

HashSet uses the same approach for storing elements as HashMap, with the difference that in HashSet the element itself acts as a key and value, in addition, HashSet does not support ordered storage of elements and provides time complexity of performing operations similar to HashMap.

What happens if you add items to the TreeSet in ascending order?

TreeSet is based on a red-black tree that can balance itself. As a result, the TreeSet doesn't care in what order you add elements to it, the benefits of this data structure will be preserved.

Difference between LinkedHashSet and HashSet

LinkedHashSet differs from HashSet only in that it is based on LinkedHashMap instead of HashMap. This makes the order of elements when traversing the collection is identical to the order of insertion of elements (insertion-order). When adding an element that is already present in the LinkedHashSet (i.e. with the same key), the order of traversing the elements does not change.

Special class for Enum, java.util.EnumSet

EnumSet is an implementation of the Set interface for use with Enum. The data structure stores objects of only one type of Enum, specified at creation. EnumSet uses a bit vector to store values, which allows for high compactness and efficiency. The EnumSet is traversed according to the order in which the enumeration elements are declared.

All basic operations are performed in O(1) and are usually (but not guaranteed) faster than HashSet counterparts, and bulk operations such as containsAll() and retainAll() are even much faster.

In addition, EnumSet provides many static initialization methods for simplified and convenient instantiation.

What are the ways to iterate over the elements of a list?

Loop with iterator

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    //iterator.next();
}

For loop

for (int i = 0; i < list.size(); i++) {
    //list.get(i);
}

While loop

int i = 0;
while (i < list.size()) {
    //list.get(i);
    i++;
}

"For-each"

for (String element : list) {
    //element;
}


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed