Java - Generics
Archive - Originally posted on "The Horse's Mouth" - 2008-11-27 16:39:56 - Graham EllisIf you're writing a Java program and you want to hold a whole series of objects of a similar type in a single variable, you can use and array ... except that you need to know HOW MANY of them there will be before you create the array.
Using the java.util package, there are numerous more flexible alternatives - you can used a Vector or ArrayList if you want an ordered collection, or a HashTable or HashMap if you want a keyed (unordered) collection from which you select elements by 'name'.
You can declare a HashMap (as an example) as follows:
HashMap results = new HashMap();
BUT when you compile your code, you'll get:
[trainee@easterton b2]$ javac Req.java
Note: Req.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
[trainee@easterton b2]$
And when you press it a bit, you get:
[trainee@easterton b2]$ javac -Xlint Req.java
Req.java:19: warning: [unchecked] unchecked call to
put(K,V) as a member of the raw type java.util.HashMap
results.put(person, firstSkill);
^
1 warning
[trainee@easterton b2]$
What's all this about?
Vectors, ArrayLists, HashMaps, and HashTables can store any object types, and the Java compiler is worried about typing - that you'll put something into one that you don't mean to, and get a run time error when you pull it out. But from Java 1.5 you can use a generic which lets you tell the java compiler what types it should accept into the collection - in the case of ArrayList and friends that will be a single type definition, and in the case of a HashMap and friends it will be two types. Here's an example:
HashMap<String,String> results = new HashMap<String,String>();
Result? A clean compile:
[trainee@easterton b2]$ javac Req.java
[trainee@easterton b2]$
And also a re-assurance that what comes back out of your collection at runtime is what you expected!