Meena Chaudhary
Meena Chaudhary

Reputation: 10715

No random access method for Java Set

I wonder why there is no random access method get(Object) like Map in Java Set. In current implementation iterating the whole collection seems as unnecessary overhead.

Upvotes: 3

Views: 2803

Answers (3)

mvd
mvd

Reputation: 2720

As other have pointed out a Set is modeled more or less after a mathematical set and does not concern itself with random access. However, if you absolutely have to access one element you can do something like this:

Set<Object> mySet = new HashSet<Object>();
mySet.add("one");
Object access = mySet.toArray()[0];

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200296

A Set is not about random element retrieval—it is about testing for the existence of elements in it. If your application calls for retrieval, then what it actually needs is an identity mapping (a map where you put(key, key)). Then you will be able to get the object just as you want. Also note that you won't be incurring any overheads by doing so because a HashSet is implemented in terms of a HashMap in almost exactly the same way.

Upvotes: 4

The Archetypal Paul
The Archetypal Paul

Reputation: 41779

> boolean   contains(Object o)
Returns true if this set contains the specified element.

(from https://docs.oracle.com/javase/7/docs/api/java/util/Set.html)

Upvotes: 4

Related Questions