What is the best way to get value from java.util.Collection
by index?
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.
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.
If you need fast access to elements using index, ArrayList should be choice.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With