Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Java 101: The next generation: The essential Java language features tour, Part 1

Java programming with assertions and generics

  • Print
  • Feedback

Page 6 of 9

The java.lang.Comparable interface is declared as a generic type with a single type parameter named T. This class provides an int compareTo(T o) method that compares the current object with the argument (of type T), returning a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

The SortedEmployees class lets you store Employee subclass instances that implement Comparable in an internal array. This array is sorted (via the java.util.Arrays class's void sort(Object[] a, int fromIndex, int toIndex) class method) in ascending order of the hourly wage after an Employee subclass instance is added.

Compile Listing 6 (javac GenDemo.java) and run the application (java GenDemo). You should observe the following output:

  • Print
  • Feedback

Resources
  • Download the source code for this article.
  • Read Angelika Langer's Java Generics FAQs for a wealth of information and perspective about generics in the Java language.
  • For students of the Java language and its controversies, Langer's "Und erstanding the closures debate" (JavaWorld, June 2008) compares the three initial proposals for adding closures, or lambda expressions, to the Java language in Java 7.
  • See "Java Reflection: Generics" (Jakob Jenkov, Jenkov.com) for further discussion about reflection with generics and special cases where it is possible to access generics information at runtime.
  • More from Java 101: The next generation:
  • More about the Java Collections Framework on JavaWorld: