Showing posts with label generics. Show all posts
Showing posts with label generics. Show all posts

Tuesday, June 11, 2013

Java 1.5 Features

Java 5 Generics

Generics provide a way to create and use typesafe data structures. This means that no longer do you have to create a List of the basic Objects then typecast every time you pull stuff out! You can declare your list to automatically typecast the stuff inside:
List things = createListOfBorkObjects();
for(Iterator i = things.iterator() ; i.hasNext() ; ) {
  Bork item = (Bork)i.next();
  //do something useful
}
Simply becomes...
List<Bork> things = createListOfBorkObjects();
for(Iterator<String> i = things.iterator() ; i.hasNext() ; ) {
  Bork item = i.next();
  //do something useful
}
The Java compiler also protects things from having non-Bork objects inside. If you try to put a String or anything else in, you'll get an error. This essentially means that you can create a list with specific types now instead of just objects. These exist in other classes such as Map which uses two:
Map<String, Bork> myMap = new HashMap<String, Bork>();
That creates a map that uses a String key and a Bork value. This implementation kind of looks like something using templates in C++...
Be careful though! You can create a string iterator that iterates over a list of non-strings that will only become an error at runtime. The compiler doesn't catch this.

Also, sometimes when using a type that can be parameterized, but not specifying the parameter type (in angle brackets) you can get lint warnings. This just means that you haven't provided a specific type, and the current definition of the type is "fuzzy" -- like lint, get it?

Read to Continue :  Java 5 For/In Loop