O'Reilly logo

Core Java™ 2 Volume II - Advanced Features, Seventh Edition by Gary Cornell, Cay S. Horstmann

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required