Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get value from Collection by index

What is the best way to get value from java.util.Collection by index?

like image 502
keo Avatar asked Jun 26 '09 08:06

keo


People also ask

Can you index a Collection in Java?

An index can be defined on a Collection property (java. util. Collection implementation) or Array. Setting such an index means that each of the Collection's or Array's items is indexed.

How do you find the index of an element in a Collection?

ArrayList. indexOf(). This method returns the index of the first occurance of the element that is specified. If the element is not available in the ArrayList, then this method returns -1.

Which Collection is faster if a record is to be retrieved using its index?

If you need fast access to elements using index, ArrayList should be choice.

What type of the Collection can use the GET index method?

The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned.


1 Answers

You shouldn't. a Collection avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List implies some form of ordering, but a Set does not.

Collection<String> myCollection = new HashSet<String>(); myCollection.add("Hello"); myCollection.add("World");  for (String elem : myCollection) {     System.out.println("elem = " + elem); }  System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]); 

gives me:

elem = World elem = Hello myCollection.toArray()[0] = World 

whilst:

myCollection = new ArrayList<String>(); myCollection.add("Hello"); myCollection.add("World");  for (String elem : myCollection) {     System.out.println("elem = " + elem); }  System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]); 

gives me:

elem = Hello elem = World myCollection.toArray()[0] = Hello 

Why do you want to do this? Could you not just iterate over the collection?

like image 105
butterchicken Avatar answered Oct 06 '22 01:10

butterchicken