Sub topic 4
The Diamond Operator and Type Inference
In the last chapter you wrote a generic class and filled in its type parameter when you made an object. You may have noticed that you typed the same type twice. This chapter shows how Java lets you skip the second one, and how the compiler works out what you meant.
The Problem: Saying the Same Thing Twice
A type argument is the real type you put in the angle brackets, like String in List<String>. Before Java 7, you had to write the type arguments on both sides of the = sign.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LongForm {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
Map<String, List<Integer>> scores = new HashMap<String, List<Integer>>();
names.add("Ada");
scores.put("Ada", new ArrayList<Integer>());
System.out.println(names + " " + scores);
}
}This code works. It is also tiring to write and hard to read. The type Map<String, List<Integer>> shows up twice in one line. If you change one side, you must remember to change the other.
The Diamond Operator
The diamond operator is an empty pair of angle brackets, <>, that you write after the class name when you create an object. It tells the compiler: "You work out the type arguments."
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DiamondDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
Map<String, List<Integer>> scores = new HashMap<>();
names.add("Ada");
scores.put("Ada", new ArrayList<>());
scores.get("Ada").add(95);
System.out.println(names); // [Ada]
System.out.println(scores); // {Ada=[95]}
}
}The name comes from the shape: <> looks a bit like a diamond. Both programs behave in exactly the same way. The diamond only saves typing. It does not change what the program does.
How the Compiler Fills In the Diamond
Type inference is the compiler's ability to figure out a type you did not write. The compiler looks for clues in the code around the diamond.
The main clue is the target type. The target type is the type the new object is going to be stored in or passed to. In List<String> names = new ArrayList<>();, the target type is List<String>. The compiler reasons like this:
- The variable needs a
List<String>. ArrayList<E>is aList<E>.- So
Emust beString. - The object is an
ArrayList<String>.
All of this happens when you compile. At run time the program has no extra work to do.
Where the Diamond Works
The target type does not have to be a variable. Since Java 8, the compiler also uses method parameters and return types as clues.
import java.util.ArrayList;
import java.util.List;
public class DiamondPlaces {
// Return type gives the clue: List<String>
static List<String> emptyNames() {
return new ArrayList<>();
}
// Parameter type gives the clue: List<Integer>
static int countItems(List<Integer> numbers) {
return numbers.size();
}
public static void main(String[] args) {
List<String> names = emptyNames();
names.add("Grace");
int count = countItems(new ArrayList<>());
System.out.println(names); // [Grace]
System.out.println(count); // 0
}
}In countItems(new ArrayList<>()), the method expects a List<Integer>. So the compiler makes an ArrayList<Integer>.
| Place you use `new X<>()` | Where the compiler finds the type | Java version |
|---|---|---|
| Variable declaration | The variable's declared type | 7 and later |
| `return` statement | The method's return type | 8 and later |
| Method argument | The method's parameter type | 8 and later |
| Anonymous class | The declared type | 9 and later |
Diamond with Anonymous Classes
An anonymous class is a class with no name that you write right where you create its one object. From Java 9 on, you can use the diamond with these as well.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class AnonymousDiamond {
public static void main(String[] args) {
Comparator<String> byLength = new Comparator<>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
};
List<String> words = new ArrayList<>(List.of("banana", "fig", "apple"));
words.sort(byLength);
System.out.println(words); // [fig, apple, banana]
}
}On Java 8, this line fails to compile. There you must write new Comparator<String>().
Common Mistakes
Mistake 1: Leaving Out the Brackets Completely
The diamond <> and no brackets at all look alike, but they do different things.
import java.util.ArrayList;
import java.util.List;
public class MissingDiamond {
public static void main(String[] args) {
List<String> good = new ArrayList<>(); // diamond: ArrayList<String>
List<String> risky = new ArrayList(); // no brackets: raw type
good.add("ok");
risky.add("also ok");
System.out.println(good + " " + risky);
}
}Without the brackets you create a raw type, which is a generic class used with no type arguments at all. The compiler gives an "unchecked" warning when you compile this program. A later chapter covers raw types in detail. For now, always type the <>.
Mistake 2: Using `var` with an Empty Diamond
The keyword var (Java 10 and later) asks the compiler to work out a variable's type from the right-hand side. The diamond asks the compiler to work out the type arguments from the left-hand side. If you use both, neither side has a clue.
import java.util.ArrayList;
public class VarPitfall {
public static void main(String[] args) {
var items = new ArrayList<>(); // becomes ArrayList<Object>
items.add("text");
items.add(42); // compiles: anything goes in
System.out.println(items); // [text, 42]
var names = new ArrayList<String>(); // clear: ArrayList<String>
names.add("Ada");
// names.add(42); // compile error, as it should be
System.out.println(names);
}
}With no clue, the compiler picks the safest type it can, which is Object. Your list now accepts anything, and you lose the checking that generics give you.
Mistake 3: Expecting Inference Without a Clue
Inference needs a target type. If you just call a method on a brand-new object, the compiler has nothing to go on.
import java.util.ArrayList;
public class NoClue {
public static void main(String[] args) {
int size = new ArrayList<>().size(); // ArrayList<Object>, which is fine here
System.out.println(size); // 0
}
}This case does no harm, because size() does not care about the element type. But if you try to add items and read them back as a specific type, you will need to write the type argument yourself.
Summary
- The diamond
<>lets the compiler fill in type arguments when you create an object. - The compiler uses the target type: a variable, a return type, or a parameter type.
- The diamond changes only what you type. The program runs the same way.
new ArrayList()with no brackets is a raw type, not a diamond.varcombined with<>gives youObject, so put the type on one side.
Exercise
What type of object does each line create? (1) List<Double> a = new ArrayList<>(); (2) var b = new ArrayList<>(); (3) var c = new ArrayList<Double>();
Show answer
(1) An ArrayList<Double>, inferred from the target type List<Double>. (2) An ArrayList<Object>, because neither side names an element type. (3) An ArrayList<Double>, because the type is written out on the right.
Exercise
A method is declared as static void register(Map<String, List<Integer>> table). Rewrite the call register(new HashMap<String, List<Integer>>()); using the diamond, and explain how the compiler knows the type arguments.
Show answer
Write register(new HashMap<>());. The method parameter type Map<String, List<Integer>> is the target type. The compiler matches HashMap<K, V> to Map<K, V>, so K is String and V is List<Integer>. This works in Java 8 and later.
Exercise
This line compiles but gives an "unchecked" warning: Map<String, Integer> ages = new HashMap();. What is wrong and how do you fix it?
Show answer
The angle brackets are missing, so new HashMap() creates a raw type and turns off type checking for that object. Fix it by adding the diamond: Map<String, Integer> ages = new HashMap<>();.