I\'m sure there\'s a good reason, but could someone please explain why the java.util.Set interface lacks get(int Index), or any similar get()
Set is an interface and some of its implementation classes are HashSet, TreeSet and LinkedHashSet. It uses HashMap under the hood to store values. Because HashMap does not preserve the order, it is not possible to get value by index.
You now must be thinking how Set is using HashMap since HashMap stores a key, value pair but the Set does not. valid question. when you add an element in Set, internally, it maintains a HashMap where the key is the element you want to enter in Set and the value is the dummy constant. Below is an internal implementation of add function. Hence, all the keys in the HashMap will have the same constant value.
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}