0

List interface allows us to get the object using get() method at an index.

How can we obtain the object at the particular index in set interface like LinkedHashSet

user3041058
  • 1,520
  • 2
  • 12
  • 16

4 Answers4

6

Set is unordered. There isn't the concept of index.

Therefore, if you want to get a particular element, you are forced to loop over it and break as soon as you find element you wanted.

Mik378
  • 21,881
  • 15
  • 82
  • 180
2

http://docs.oracle.com/javase/7/docs/api/java/util/Set.html

and here: http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html

But a set is only used to check if something is in the list, not where it is.

Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49
1

You can't. There is no indexed acces for a set since it is not ordered.

André Stannek
  • 7,773
  • 31
  • 52
1

Short answer is, it is not possible. However, you can get an array that has all datum from the Set you are using and then accessing it via an index. This has to do with the abstraction provided by Set which is different from List.

A Set is simply a collection that does not allow duplicates (no comments on ordering), but a List is a collection that implies ordering, so each value has an associated index.

prmottajr
  • 1,816
  • 1
  • 13
  • 22
  • `LinkedList` in fact has an order, [*the order in which elements were inserted into the set (insertion-order)*](http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html). It does not provide direct accessors, though. Your recommendation, to convert to an array is the right answer, though. – Moritz Petersen Dec 09 '13 at 12:50
  • @Moritz, you are right, but LinkedHashSet isn't a LinkedList, it contains a LinkedList, so it doesn't expose this feature to the user :) that was my line of thought. – prmottajr Dec 09 '13 at 12:59
  • @prmottajr Caution to the term: it does not contains a `LinkedList` but a "linked list" in generic term. Actually `LinkedHashSet` is based on a `LinkedHashMap`, not a `LinkedList`. – Mik378 Dec 10 '13 at 08:13