The maximum element in an array in Java (Collections.max () for whole arrays int [])

Is there something like Collections.max that finds the maximum value in an array for regular arrays in the standard java time library?

+4
source share
5 answers

No, no Arrays.max or ranger, at least in Java 6.

If you look at the signature and implementation of Collections.max, it pretty much uses parameterized types. In Java, typical arrays are at least problematic, which is why, perhaps, it is therefore not recommended to provide a universal max implementation for arrays in Java and keep the focus on collections (shared).

Edit: as newacct correctly points out, using shared arrays is not necessarily more problematic than using shared collections, so I edited the above text as the original was wrong. However, the main argument of “shared arrays is problematic” is still valid, and collections should be preferred over arrays of reference types.

 public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)max((Collection<SelfComparable>) (Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) > 0) candidate = next; } return candidate; } 
+1
source

If you have an array of objects, you can use

 Collections.max(Arrays.asList(array)); 

If you have an array of primitives, you can just use a simple loop.

 long[] array; long max = array[0]; for(long l : array) if (max < l) max = l; 
+6
source

You can use Arrays.sort (int []) and then access the first (or last) element. Or you can just iterate over the array and look for the largest / largest element. It is basically no problem.

+1
source

You can also create a decorator for the Collection, which contains additional methods such as getMaximumValue (), and update the return value each time an element is added / removed, if necessary.

This would make sense, although if you used the maximum value in your program, it would mean that iterating through the list would lead to significant overhead.

0
source

As far as I know, no. You can look at asList ( http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#asList (T ...) ), but this is probably not worth it.

-2
source

All Articles