Reading old Java

Java before version 5 had no generics: a collection held Object, and every read needed a cast. Those classes are still in the JDK, still work, and still appear in code written before 2004 and in code copied from it since. This lesson reads such a class, shows what -Xlint:all says about it, why the compiler is right to complain, and what the same code looks like today.

Vector and Hashtable

Vector and Hashtable are the original collection classes of Java 1.0, and Enumeration is the original way to walk them. They are still in the JDK, synchronised on every method, and the compiler says something about every use below:

import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; public class Old { public static void main(String[] args) { Vector names = new Vector(); names.addElement("Ada"); names.addElement(42); Hashtable ages = new Hashtable(); ages.put("Ada", 36); ages.put("Grace", 45); Enumeration e = names.elements(); while (e.hasMoreElements()) { System.out.println(e.nextElement()); } Enumeration keys = ages.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + " is " + ages.get(key)); } } }

javac -Xlint:all Old.java
java Old

Old.java:7: warning: [rawtypes] found raw type: Vector
Vector names = new Vector();
^
missing type arguments for generic class Vector<E>
where E is a type-variable:
E extends Object declared in class Vector
Old.java:7: warning: [rawtypes] found raw type: Vector
Vector names = new Vector();
^
missing type arguments for generic class Vector<E>
where E is a type-variable:
E extends Object declared in class Vector
Old.java:8: warning: [unchecked] unchecked call to addElement(E) as a member of the raw type Vector
names.addElement("Ada");
^
where E is a type-variable:
E extends Object declared in class Vector
Old.java:9: warning: [unchecked] unchecked call to addElement(E) as a member of the raw type Vector
names.addElement(42);
^
where E is a type-variable:
E extends Object declared in class Vector
Old.java:11: warning: [rawtypes] found raw type: Hashtable
Hashtable ages = new Hashtable();
^
missing type arguments for generic class Hashtable<K,V>
where K,V are type-variables:
K extends Object declared in class Hashtable
V extends Object declared in class Hashtable
Old.java:11: warning: [rawtypes] found raw type: Hashtable
Hashtable ages = new Hashtable();
^
missing type arguments for generic class Hashtable<K,V>
where K,V are type-variables:
K extends Object declared in class Hashtable
V extends Object declared in class Hashtable
Old.java:12: warning: [unchecked] unchecked call to put(K,V) as a member of the raw type Hashtable
ages.put("Ada", 36);
^
where K,V are type-variables:
K extends Object declared in class Hashtable
V extends Object declared in class Hashtable
Old.java:13: warning: [unchecked] unchecked call to put(K,V) as a member of the raw type Hashtable
ages.put("Grace", 45);
^
where K,V are type-variables:
K extends Object declared in class Hashtable
V extends Object declared in class Hashtable
Old.java:15: warning: [rawtypes] found raw type: Enumeration
Enumeration e = names.elements();
^
missing type arguments for generic class Enumeration<E>
where E is a type-variable:
E extends Object declared in interface Enumeration
Old.java:19: warning: [rawtypes] found raw type: Enumeration
Enumeration keys = ages.keys();
^
missing type arguments for generic class Enumeration<E>
where E is a type-variable:
E extends Object declared in interface Enumeration
10 warnings
Ada
42
Grace is 45
Ada is 36

Ten warnings and four lines of output, from one run. The program works, and that is exactly the trap: a warning that a code base has decided to ignore is a promise nobody keeps. The two Hashtable lines come out in hash order, not in the order they were put in.

The warnings -Xlint:all prints

[rawtypes] points at a use of a generic class without its type arguments, and it appears twice for Vector names = new Vector(): once for the variable and once for the constructor. [unchecked] is worse: the call itself cannot be checked, because a raw Vector accepts any element and the compiler has no promise to verify. The warning ends the same way every time, with the type variable the class declares.

Two line labels are worth knowing. [rawtypes] is about the declaration and is fixed by writing the type arguments. [unchecked] is about a call and is fixed by the same change, because a Vector<String> checks its elements at compile time. Neither warning stops the build, and -Werror would, which is the setting a new project uses.

The cast that fails at run time

The unchecked call accepts a String into a vector the program believes is full of integers. The loop that sums it casts every element, and the cast fails on the second one, at run time, in a line that looks safe:

import java.util.Vector; public class Crash { public static void main(String[] args) { Vector numbers = new Vector(); numbers.add(1); numbers.add("two"); int sum = 0; for (Object value : numbers) { sum += (Integer) value; } System.out.println(sum); } }

javac -Xlint:all Crash.java
java Crash
echo "status: $?"

Crash.java:5: warning: [rawtypes] found raw type: Vector
Vector numbers = new Vector();
^
missing type arguments for generic class Vector<E>
where E is a type-variable:
E extends Object declared in class Vector
Crash.java:5: warning: [rawtypes] found raw type: Vector
Vector numbers = new Vector();
^
missing type arguments for generic class Vector<E>
where E is a type-variable:
E extends Object declared in class Vector
Crash.java:6: warning: [unchecked] unchecked call to add(E) as a member of the raw type Vector
numbers.add(1);
^
where E is a type-variable:
E extends Object declared in class Vector
Crash.java:7: warning: [unchecked] unchecked call to add(E) as a member of the raw type Vector
numbers.add("two");
^
where E is a type-variable:
E extends Object declared in class Vector
4 warnings
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
at Crash.main(Crash.java:10)
status: 1

The exception names both classes and the module they came from, and the frame gives the line. That is what an unchecked warning buys: the check moved from the build to the run, and the run happens later, on someone else's machine, with a value nobody predicted.

The modernised class

Every warning above disappears with a type parameter, and the code gets shorter: ArrayList and HashMap replace the two old classes, the for-each replaces the Enumeration, and the cast disappears because the loop knows the element type:

import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class Modern { public static void main(String[] args) { List<Object> names = new ArrayList<>(); names.add("Ada"); names.add(42); Map<String, Integer> ages = new LinkedHashMap<>(); ages.put("Ada", 36); ages.put("Grace", 45); for (Object name : names) { System.out.println(name); } for (Map.Entry<String, Integer> entry : ages.entrySet()) { System.out.println(entry.getKey() + " is " + entry.getValue()); } } }

javac -Xlint:all Modern.java
java Modern

Ada
42
Ada is 36
Grace is 45

The build prints nothing, and the map now prints in insertion order because LinkedHashMap keeps it. The one deliberate Object element is honest: the list really does hold a string and a number, so its type argument is Object and a reader can see that. When a list holds one type, the argument says which, and the cast disappears everywhere.

Deprecated for removal

The second kind of old code is a constructor that still exists and should not be called. new Integer(42) is deprecated for removal, and -Xlint:all reports the tag it carries:

public class Boxed { public static void main(String[] args) { Integer old = new Integer(42); Integer modern = Integer.valueOf(42); System.out.println(old + " " + modern); System.out.println(old.equals(modern)); } }

javac -Xlint:all Boxed.java
java Boxed

Boxed.java:3: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
Integer old = new Integer(42);
^
1 warning
42 42
true

[removal] is stronger than [deprecation]: the member is expected to disappear in a future release, so a program that keeps calling it has a date on it. Integer.valueOf does the same thing and caches the small values, which is lesson 029.

Rules for reading old code

Read the warnings before the code, because they name the places where the compiler stopped checking. Treat a raw type as a question: which type does this collection really hold, and is the answer one type or several? A Vector field in an old class is usually an ArrayList with a type argument, and a Hashtable is a HashMap unless the synchronisation is load-bearing.

Keep the Enumeration loops until the surrounding code is rewritten, and change the type arguments first: that change is local, it removes most of the warnings, and it proves which elements the collection holds. The unchecked warning that remains after that is the real one, and lesson 068 explains why some of them cannot be removed.

Exercises

  1. Add a type argument to the Vector of Crash.java that makes the second add a compile error.
  2. Change Old.java to use Vector<String> and count the warnings that remain.
  3. Replace the Enumeration loop of Old.java with a for-each and print the same lines.
  4. Build Boxed.java with -Werror and read the failure.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a raw type mean?

    Answer

    A generic class used without its type arguments

    Vector without <E> is a raw type, and the compiler cannot check what it holds.

  2. What does an [unchecked] warning say?

    Answer

    The compiler cannot verify the types at that call

    The check is skipped because the raw type carries no information, so it moves to run time.

  3. Which collection replaces Vector in new code?

    Answer

    ArrayList

    ArrayList is the unsynchronised list, and Vector is kept for compatibility.

  4. What does this program print? import java.util.Vector; public class Q1 { public static void main(String[] args) { Vector v = new Vector(); v.add("a"); v.add("b"); System.out.println(v.size()); System.out.println(v.get(1)); } }

    Answer

    2 then b

    The raw vector holds both elements, and get(1) is the second.

  5. What does this program print? import java.util.ArrayList; import java.util.List; public class Q2 { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); int sum = 0; for (int n : numbers) { sum += n; } System.out.println(sum); } }

    Answer

    3

    A typed list needs no cast, and the loop adds the two numbers.

  6. What happens at run time in this program? import java.util.ArrayList; import java.util.List; public class Q3 { public static void main(String[] args) { List<Object> values = new ArrayList<>(); values.add("x"); try { int n = (Integer) values.get(0); System.out.println(n); } catch (ClassCastException e) { System.out.println("ClassCastException"); } } }

    Answer

    ClassCastException

    The cast of a String to Integer is checked at run time and fails there.

  7. What does this program print? import java.util.Hashtable; public class Q4 { public static void main(String[] args) { Hashtable ages = new Hashtable(); ages.put("a", 1); System.out.println(ages.get("a")); System.out.println(ages.get("b")); } }

    Answer

    1 then null

    A missing key gives null, and the raw type hides that it could be anything.

  8. What does [removal] mean in a warning?

    Answer

    The member is deprecated and expected to be removed in a future release

    It is the strongest deprecation tag, and the member is expected to disappear.

  9. What does adding a type argument to a raw collection remove?

    Answer

    The rawtypes and unchecked warnings at that declaration and its calls

    With the argument known, the compiler checks each call and both warnings go.

  10. What does -Werror do?

    Answer

    Turns every warning into an error and fails the build

    A project that wants no warnings in its code fails the build when one appears.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev