Generics,
Introduction
- The Java Generics features were added to the Java language from Java 5.
- Generics add a way to specify concrete types to general purpose classes and methods that operated on
Object
before. - It sounds a bit abstract, so we will look at some examples using collections right away. Note: Generics can be used with other classes than the collection classes, but it is easiest to show the basics using collections.
The
List
interface represents a list of Object
instances. This means that we could put any object into a List
. Here is an example:List list = new ArrayList(); list.add(new Integer(2)); list.add("a String");
Because any object could be added, you would also have to cast any objects obtained from these objects. For instance:
Integer integer = (Integer) list.get(0); String string = (String) list.get(1);
Very often you only use a single type with a collection. For instance, you only keep
String
's or something else in the collection, and not mixed types like I did in the example above.
With Java's Generics features you can set the type of the collection to limit what kind of objects can be inserted into the collection. Additionally, you don't have to cast the values you obtain from the collection. Here is an example using Java's Generic's features:
List<String> strings = new ArrayList<String>(); strings.add("a String"); String aString = strings.get(0);
Nice, right?
Java 5 also got a new for-loop (also referred to as "for-each") which works well with generified collections. Here is an example:
List<String> strings = new ArrayList<String>(); //... add String instances to the strings list... for(String aString : strings){ System.out.println(aString); }
This for-each loop iterates through all
String
instances kept in the strings
list. For each iteration, the nextString
instance is assigned to the aString
variable. This for-loop is shorter than original while-loop where you would iterate the collections Iterator
and call Iterator.next()
to obtain the next instance.
Just awesome.
ReplyDeleteThe image clears everything.