I used Collections.sort(playersList);
to sort a List
. So, I think playersList
is sorted now. But how can I get the first element of the list? playersList[0]
does not work.
views:
171answers:
6playersList.get(0)
Java has limited operator polymorphism. So you use the get()
method on List
objects, not the array index operator ([]
)
You have to access lists a little differently than arrays in Java. See the javadocs for the List
interface for more information.
playersList.get(0)
However if you want to find the smallest element in playersList
, you shouldn't sort it and then get the first element. This runs very slowly compared to just searching once through the list to find the smallest element.
For example:
int smallestIndex = 0;
for (int i = 1; i < playersList.size(); i++) {
if (playersList.get(i) < playersList.get(smallestIndex))
smallestIndex = i;
}
playersList.get(smallestIndex);
The above code will find the smallest element in O(n)
instead of O(n log n)
time.
That depends on what type your list is, for ArrayList
use:
list.get(0);
for LinkedList
use:
list.getFirst();
if you like the array
approach:
list.toArray()[0];
Matthew's answer is correct:
list.get(0);
To do what you tried:
list[0];
you'll have to wait until Java 7 is released:
Here's an interesting presentation by Mark Reinhold about Java 7
It looks like parleys site is currently down, try later :(
If your collection is not a List
(and thus you can't use get(int index)
), then you can use the iterator:
Iterator iter = collection.iterator();
if (iter.hasNext()) {
Object first = iter.next();
}
If you just want to get the minimum of a list, instead of sorting it and then getting the first element (O(N log N)
), you can use do it in linear time using min
:
<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
That looks gnarly at first, but looking at your previous questions, you have a List<String>
. In short: min
works on it.
For the long answer: all that super
and extends
stuff in the generic type constraints is what Josh Bloch calls the PECS principle (usually presented next to a picture of Arnold -- I'M NOT KIDDING!)
Producer Extends, Consumer Super
It essentially makes generics more powerful, since the constraints are more flexible while still preserving type safety (see: what is the difference between ‘super’ and ‘extends’ in Java Generics)