Algorithms

Generic collection interfaces have a great advantage—you only need to implement your algorithms once. For example, consider a simple algorithm to compute the maximum element in a collection. Traditionally, programmers would implement such an algorithm as a loop. Here is how you find the largest element of an array.

if (a.length == 0) throw new NoSuchElementException();
T largest = a[0];
for (int i = 1; i < a.length; i++)
   if (largest.compareTo(a[i]) < 0) 
      largest = a[i];

Of course, to find the maximum of an array list, you would write the code slightly differently.

 if (v.size() == 0) throw new NoSuchElementException(); T largest = v.get(0); for (int i = 1; i < v.size(); i++) if (largest.compareTo(v.get(i)) < 0) largest = v.get(i); ...

Get Core Java™ 2 Volume II - Advanced Features, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.