Sub topic 17
Raw Types and Unchecked Warnings
In the first chapter you saw a list with no type in angle brackets. That kind of list is called a raw type. This chapter explains what raw types are, why Java still allows them, and what the compiler's "unchecked" warnings mean. You will also learn how to fix those warnings and when it is acceptable to hide one.
What Is a Raw Type?
A raw type is a generic class or interface used without any type argument. A type argument is the real type you put in the angle brackets, such as String in List<String>.
| Code | What it is |
|---|---|
| `List<String>` | A parameterized type. The compiler knows it holds `String` values. |
| `List` | A raw type. The compiler does not know what it holds. |
| `ArrayList<>` | A diamond. The compiler infers the type argument, so this is not raw. |
| `new ArrayList()` | A raw type. There are no angle brackets at all. |
When you use a raw type, the compiler turns off generic type checking for that variable. It treats every element as a plain Object.
Why Raw Types Still Exist
Generics were added in Java 5, in 2004. Millions of lines of Java code had already been written before then, and none of it used angle brackets. To keep that old code working, the designers let generic types be used without type arguments. This is called backward compatibility: new versions of Java can still compile and run old code.
Type erasure, which you met two chapters ago, makes this possible. At runtime, List<String> and List are the same class. So old raw code and new generic code can pass lists to each other.
The Danger: Mixing Raw and Generic Code
The real trouble starts when raw code and generic code meet. The compiler cannot check what a raw list contains, so it must trust you when you treat that list as a List<String>. If that trust is wrong, the error shows up later, far from where the mistake was made.
import java.util.ArrayList;
import java.util.List;
public class RawMixDemo {
// Imagine this method comes from an old library written before Java 5.
static List makeLegacyList() {
List list = new ArrayList(); // raw type
list.add("apple");
list.add(7); // the old code slips in an Integer
return list;
}
public static void main(String[] args) {
List<String> words = makeLegacyList(); // compiles, with a warning
System.out.println("Got a list of size " + words.size());
for (String w : words) { // the hidden cast fails on the Integer
System.out.println(w.toUpperCase());
}
}
}Running this program prints:
Got a list of size 2
APPLE
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.StringThe bad value went in inside makeLegacyList, but the crash happens inside the loop in main. In a large program those two places could be in different files. That is why this kind of bug is hard to find.
Reading Unchecked Warnings
An unchecked warning is the compiler's way of saying: "I cannot prove this is type safe, so I am trusting you." It is a warning, not an error, so the program still compiles.
By default, javac shows only a short note:
Note: RawMixDemo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.The -Xlint option asks the compiler for detailed warnings. Run it like this:
javac -Xlint:unchecked RawMixDemo.javaNow you see each problem line:
RawMixDemo.java:9: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
list.add("apple");
^
RawMixDemo.java:15: warning: [unchecked] unchecked conversion
List<String> words = makeLegacyList(); // compiles, with a warning
^
required: List<String>
found: ListIf you use -Xlint:all, you also get [rawtypes] warnings, which point to every place a raw type is written.
The common kinds of warnings are listed here:
| Warning | What triggered it |
|---|---|
| `[rawtypes]` | You wrote a generic type with no type argument, such as `List`. |
| unchecked call | You called a method like `add` on a raw type. |
| unchecked conversion | You assigned a raw type to a parameterized type. |
| unchecked cast | You cast an object to a parameterized type, such as `(List<String>) obj`. |
Fixing the Warnings
The best fix is almost always to add type arguments. Here is the same program written without raw types:
import java.util.ArrayList;
import java.util.List;
public class FixedDemo {
static List<String> makeList() {
List<String> list = new ArrayList<>();
list.add("apple");
// list.add(7); // now a compile error, caught right here
list.add("pear");
return list;
}
public static void main(String[] args) {
List<String> words = makeList();
for (String w : words) {
System.out.println(w.toUpperCase());
}
}
}The mistake that crashed the first program is now a compile error, on the exact line where it happens.
Sometimes a list really can hold anything. Even then, do not use a raw type. Choose one of these:
| Type | Can you add to it? | Is it type checked? | Use it when |
|---|---|---|---|
| `List` (raw) | Yes, anything | No | Never in new code |
| `List<Object>` | Yes, any object | Yes | The list really holds mixed objects |
| `List<?>` | No, except `null` | Yes | You only read, and the element type does not matter |
List<?> accepts any list, just like a raw List, but the compiler stops you from adding the wrong thing to it.
Hiding a Warning with @SuppressWarnings
Sometimes you cannot avoid an unchecked operation. For example, an old library might return a plain Object that you know is a list of strings. In that case you can use the @SuppressWarnings("unchecked") annotation. An annotation is a label that starts with @ and gives extra information to the compiler.
import java.util.ArrayList;
import java.util.List;
public class SuppressDemo {
static Object legacyLookup() {
List<String> names = new ArrayList<>();
names.add("Ada");
return names;
}
public static void main(String[] args) {
Object result = legacyLookup();
// Safe: legacyLookup is documented to return only a list of strings.
@SuppressWarnings("unchecked")
List<String> names = (List<String>) result;
System.out.println(names.get(0));
}
}Follow these rules when you suppress a warning:
- First make sure the code really is safe.
- Put the annotation on the smallest piece of code you can, such as one variable declaration. Do not put it on a whole class.
- Write a comment that explains why the operation is safe.
Places Where Raw Names Are Required
There are two places where you must write the raw name. Neither causes a warning.
- Class literals:
List.classis allowed, andList<String>.classis not. Erasure means there is only oneListclass. instanceofchecks:obj instanceof Listworks.obj instanceof List<?>is also allowed and is the clearer choice.
Exercise
The line List<Integer> scores = oldApi.getScores(); gives the warning "unchecked conversion, required: List<Integer>, found: List". What does this warning mean, and what could go wrong at runtime?
Show answer
The method returns a raw List, so the compiler cannot check that it contains only Integer values. It allows the assignment but warns you. If the list actually contains something else, such as a String, a ClassCastException will occur later, when code reads that element as an Integer.
Exercise
A method should accept any kind of list and print its size and elements. A teammate wrote static void show(List items). Rewrite the parameter so that it accepts any list without using a raw type.
Show answer
Use the unbounded wildcard: static void show(List<?> items). It accepts List<String>, List<Integer>, and any other list, the elements can still be read as Object, and the compiler prevents adding values of the wrong type.
Exercise
Why is putting @SuppressWarnings("unchecked") on an entire class a bad idea?
Show answer
It hides every unchecked warning in the class, including warnings from future code that may really be unsafe. Put the annotation on the smallest possible declaration, and only after you have confirmed that the operation is safe.