Here are some personal notes for the Java programming language.
The primary audience is myself. I will attempt to be as brief as possible with these notes, except in cases where I found the material to be tricky or different from both C++ and Java.
JDK 1.5 introduces a language extension called generics. Generics introduce compile-time type checking to Java's container classes, so code like this:
List myIntList = new LinkedList(); myIntList.add(new Integer(0)); Integer x = (Integer) myIntList.iterator().next();May be instantiated and used like this like this:
List<Integer> myIntList = new LinkedList<Integer>(); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next();Note how on the second line, compile-time type checking can now happen on add method. myIntList is now guaranteed to only hold integers, and not any object as before. Also, observe how on the third line no casting is required on the assignment statement.
A generic type is defined as such:
class Pair<X,Y> {
private X first;
private Y second;
public Pair(X a1, Y a2) {
first = a1;
second = a2;
}
public X getFirst() { return first; }
public Y getSecond() { return second; }
public void setFirst(X arg) { first = arg; }
public void setSecond(Y arg) { second = arg; }
}
An example of using our newly defined generic type:
Pair<String,Long> limit = new Pair<String,Long>("maximum",1024L);
This is how to use a generic as a part of a method parameter:
/**
* Removes 4-letter words from aList of Strings
**/
public static void Expurgate(List<String> aList) {
// This is a nice way to iterate over a collection
for (Iterator<String> it = aList.iterator(); it.hasNext(); ) {
String s = it.next(); // No downcasting required.
if (s.length() == 4) {
it.remove();
}
}
}
As you can see, the expurgate method can only accept collections of strings.
public static <A extends Comparable<A>> A max(Collection< A > xs) {
Iterator< A > xi = xs.iterator();
A w = xi.next();
while (xi.hasNext()) {
A x = xi.next();
if (w.compareTo(x) < 0) w = x;
}
return w;
}
A wildcard describes a family of types. There are 3 different flavors of wildcards:
Here are some examples of wildcard parameterized types:
Collection<?> coll = new ArrayList<String>();
List<? extends Number> list = new ArrayList<Long>();
Compararator<? super String> cmp = new RuleBasedCollator("< a< b< c< d");
Pair<String,?> pair = new Pair<String,String>();
Note the use of extends here:
Wrapper <? extends Number> wrapper2 = new Wrapper <Long> (0L); Wrapper <Number> wrapper4 = new Wrapper <Number> (new Long(0L)); // error