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
June 7, 2001-- The lack of generic types in the Java programming language has been a source of controversy for years. All of that is starting to change as JSR-014, "Add Generic Types to the Java Programming Language," makes its way through the Java Community Process (JCP). Generic types are coming to Java -- one of these days.
On Tuesday at the JavaOne Conference, Gilad Bracha, computational theologist at Sun Microsystems and specification lead of JSR-014, presented the technical session entitled "Adding Generics to the Java Programming Language" (TS-2733) to a sold-out crowd. The enormous turnout -- many stood outside the packed hall listening to the presentation on speakers -- demonstrated the importance of the generics topic.
import java.util.*;
public class DangerousLoop
{
public static void main( String [] args )
{
List l = new ArrayList();
Integer i1 = new Integer( 1 );
Integer i2 = new Integer( 2 );
String i3 = "3";
Integer i4 = new Integer( 4 );
l.add( i1 );
l.add( i2 );
l.add( i3 );
l.add( i4 );
System.out.println( sum( l ) );
}
public static int sum( List l )
{
Iterator numbers = l.iterator();
int counter = 0;
while( numbers.hasNext() )
{
Integer integer = (Integer) numbers.next();
counter += integer.intValue();
}
return counter;
}
}The public static int sum( List l ) method expects a List of Integers. The method loops over each element in the List, casts it back to its expected type, and sums the value. This simple example demonstrates how you would have to handle lists
in Java. However, it also exemplifies many of the shortcomings that the lack of generics brings.
First, consider the main() method that sets up the Listthat is sent to the sum() method. You will notice that main() inserts Integers and a String into the list. Of course, calling the sum90 method on this Listwill result in a ClassCastException because it will try to cast a String to an Integer.
Heterogeneous collections such as those found in Java are not type safe because you can put many different types of objects
into the collection at the same time. A lack of type safety is not always a problem. However, in order to do anything beyond
the methods defined on the Object base class, you will have to cast the object back to its actual type. As this example shows, such indiscriminate casts can
be dangerous. You can do an instance of check to avoid the ClassCastException; however, this extra check can add weight to your code (and is not very object oriented, for that matter).
Extra casting is also a performance problem, and it clutters the readability of code. All in all, a lack of generics results in extra headaches for the developer.
The next example presents a new List that takes advantage of generics. (Please note that this List's interface is simplified for brevity's sake):