best way to find maximum age element of List
List<Man> list=new ArrayList<Man>();
Man manA = new Man(29); // constructor parameter is age, use manA.age to get 29
list.add(manA);
Man manB = new Man(23);
list.add(manB);
Man manC = new Man(42);
list.add(manC);
Man manD = new Man(38);
list.add(manD);
I want get the 开发者_JS百科maximum age element manC
in list
,
What's the best(fastest) way to do this?
No matter what, you're going to have to do it in O(N) time unless you use something other than a list.
Man maxAge = new Man(0);
for(Man man : list) {
if(man.age > maxAge.age) {
maxAge = man;
}
}
This will simply go through the entire list, recording the man with the greatest age it has encountered yet. When the loop is finished, maxAge will be the oldest of them all.
Edit:
In response to your comment about Collections.max being "better", I thought I'd just include this note just so no one is confused. It is better in the sense that interfacing a comparator is good practice and the fact that it is part of java.util is nice too. However, if you look at the source code (attached below) it does exactly the same thing. So algorithmically, it is not better (faster, as you mentioned above).
public static <T extends Object & Comparable<? super T>> T max(
Collection<? extends T> collection) {
Iterator<? extends T> it = collection.iterator();
T max = it.next();
while (it.hasNext()) {
T next = it.next();
if (max.compareTo(next) < 0) {
max = next;
}
}
return max;
}
Or you could add the Man objects to TreeSet which uses Red-Black tree underlying. That means the tree maintains the order when adding. It's O(log(N)).
Man maxAge = null;
for (Man man: list)
{
if (maxAge==null || man.getAge() > maxAge.getAge())
maxAge = man;
}
精彩评论