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()
To get element in a Set, i use to following one:
public T getElement(Set<T> set, T element) {
T result = null;
if (set instanceof TreeSet<?>) {
T floor = ((TreeSet<T>) set).floor(element);
if (floor != null && floor.equals(element))
result = floor;
} else {
boolean found = false;
for (Iterator<T> it = set.iterator(); !found && it.hasNext();) {
if (true) {
T current = it.next();
if (current.equals(element)) {
result = current;
found = true;
}
}
}
}
return result;
}
You can do new ArrayList<T>(set).get(index)
That's true, element in Set are not ordered, by definition of the Set Collection. So they can't be access by an index.
But why don't we have a get(object) method, not by providing the index as parameter, but an object that is equal to the one we are looking for? By this way, we can access the data of the element inside the Set, just by knowing its attributes used by the equal method.
That is because Set only guarantees uniqueness, but says nothing about the optimal access or usage patterns. Ie, a Set can be a List or a Map, each of which have very different retrieval characteristics.
java.util.Set
is a collection of un-ordered items. It doesn't make any sense if the Set has a get(int index), because
Set doesn't has an index and also you only can guess the value.
If you really want this, code a method to get random element from Set.
Because sets have no ordering. Some implementations do (particularly those implementing the java.util.SortedSet
interface), but that is not a general property of sets.
If you're trying to use sets this way, you should consider using a list instead.