Sub topic 7
Generics and the Diamond Operator with var
This chapter covers what var infers when the initializer involves generics. It assumes you know basic generics (List<String>, type arguments), the diamond operator <> at a basic level, and how var infers a type from its initializer. The central point is that var removes the declared type from the left side, and the diamond needs that declared type to infer its type arguments.
How the diamond works without var
The diamond operator asks the compiler to fill in the type arguments of a constructor call. It does this with two sources of information: the target type (the declared type on the left of =) and the constructor arguments.
import java.util.ArrayList;
import java.util.List;
public class DiamondTargets {
public static void main(String[] args) {
List<String> declared = new ArrayList<>(); // E inferred as String from the target
declared.add("text");
var loose = new ArrayList<>(); // no target type: ArrayList<Object>
loose.add("text");
loose.add(42); // allowed: element type is Object
System.out.println(declared); // [text]
System.out.println(loose); // [text, 42]
}
}With List<String> declared, the compiler reads String from the left side. With var loose, the left side carries no information, so the compiler has nothing to read. It falls back to the bound of the type parameter, which is Object for ArrayList<E>. The result is ArrayList<Object>, and the compiler accepts both a String and an int (boxed to Integer) without complaint.
This is the most common generics mistake with var. Nothing fails to compile. The collection simply becomes less type-safe than you intended.
Three ways to get the type you want
You have three options, and the right one depends on how much of the concrete class you want to expose.
- Put the type argument on the right:
var names = new ArrayList<String>();. The variable type isArrayList<String>. - Keep the explicit declaration and the diamond:
List<String> names = new ArrayList<>();. The variable type isList<String>. - Pass an argument that fixes the type, such as an existing collection (see the next section).
Option 1 repeats the type argument once, where the diamond would repeat it once too, so it costs no extra typing compared with the old explicit style. If you write var x = new ArrayList<>(); and meant something more specific, you are missing a type argument.
Constructor arguments can fix the type argument
The diamond infers from arguments as well as from the target. When an argument carries the element type, var with a diamond works as you would hope.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DiamondArguments {
public static void main(String[] args) {
List<String> source = List.of("a", "b");
var copy = new ArrayList<>(source); // ArrayList<String>
copy.add("c");
// copy.add(1); // would not compile
var sized = new ArrayList<>(10); // ArrayList<Object>: 10 is the capacity, not an element
sized.add("any");
sized.add(1);
var empty = List.of(); // List<Object>
var ages = Map.of("Ada", 36); // Map<String, Integer>
System.out.println(copy); // [a, b, c]
System.out.println(sized); // [any, 1]
System.out.println(empty); // []
System.out.println(ages); // {Ada=36}
}
}The ArrayList(Collection<? extends E>) constructor receives a List<String>, so the compiler infers E as String. The ArrayList(int) constructor mentions no E at all, so nothing constrains it, and you get ArrayList<Object> again. An argument only helps when its type is connected to the type parameter.
The same rule applies to generic factory methods. List.of("a", "b") produces List<String> and Map.of("Ada", 36) produces Map<String, Integer>, because the arguments determine E, K and V. List.of() has no arguments, so it produces List<Object>. The same happens with Collections.emptyList().
| Declaration | Inferred variable type |
|---|---|
| `var a = new ArrayList<>();` | `ArrayList<Object>` |
| `var b = new ArrayList<String>();` | `ArrayList<String>` |
| `var c = new ArrayList<>(List.of(1, 2));` | `ArrayList<Integer>` |
| `var d = new ArrayList<>(10);` | `ArrayList<Object>` |
| `var e = List.of("x", "y");` | `List<String>` |
| `var f = List.of();` | `List<Object>` |
| `var g = Map.of("k", 1);` | `Map<String, Integer>` |
| `var h = new HashMap<String, List<Integer>>();` | `HashMap<String, List<Integer>>` |
The variable gets the concrete class type
An explicit declaration usually names an interface (List<String>). With var, the variable gets the type of the expression, which is the concrete class.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ConcreteTypes {
public static void main(String[] args) {
List<String> declared = new ArrayList<>();
var inferred = new ArrayList<String>();
inferred.ensureCapacity(100); // ArrayList method is available
// declared.ensureCapacity(100); // would not compile: List has no such method
declared = new LinkedList<>(); // fine: the variable type is List<String>
// inferred = new LinkedList<>(); // would not compile: the variable type is ArrayList<String>
System.out.println(declared.size() + " " + inferred.size()); // 0 0
}
}There are two consequences:
- You can call methods that exist only on the class, such as
ensureCapacity. This can be useful, but it also lets code depend on an implementation detail you may not want to expose. - You cannot later assign a different implementation. If the design intent is "any
List", declareList<String>explicitly.
This matters most for fields and method signatures, where you should program to interfaces. Local variables are a narrower scope, so the concrete type does less harm there. Still, if a local later needs to switch from ArrayList to LinkedList, an explicit List declaration makes that change a one-line edit.
Wildcards and captured types
Generic methods sometimes return types that involve wildcards. When a declared variable has a wildcard type, var uses the type of the expression, and the compiler converts any internal capture type back to something you could write in source (an upward projection).
import java.util.List;
public class WildcardVar {
public static void main(String[] args) {
List<? extends Number> numbers = List.of(1, 2.5);
var first = numbers.get(0); // Number
var same = numbers; // List<? extends Number>
System.out.println(first.intValue()); // 1
System.out.println(same.size()); // 2
}
}numbers.get(0) has the capture type "some unknown subtype of Number". The compiler cannot let you name that type, so first becomes Number. In practice, you get the same type you would have written by hand. The edge case matters only when you read compiler messages that mention capture of ? extends Number.
Where var improves generic code
The strongest benefit appears where generic types become long. Iterating over map entries is the standard example:
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class EntryLoop {
public static void main(String[] args) {
Map<String, List<Integer>> scores = new TreeMap<>();
scores.put("Ada", List.of(90, 95));
scores.put("Bo", List.of(70));
for (var entry : scores.entrySet()) { // Map.Entry<String, List<Integer>>
var name = entry.getKey(); // String
var values = entry.getValue(); // List<Integer>
System.out.println(name + " -> " + values.size());
}
}
}Here the explicit alternative is Map.Entry<String, List<Integer>> entry, which adds noise without adding information. The entrySet() call and the declared type of scores are on screen, so the reader can still work out each type.
Raw types
If you leave out the type arguments completely, you get a raw type. var raw = new ArrayList(); has type ArrayList (raw). The compiler emits an unchecked warning when you call raw.add(...), and get returns Object. This is the same as the pre-generics behavior. var does not make raw types any safer, and it makes them easier to write by accident because the left side no longer shows the missing type arguments.
Summary of rules
- The diamond takes its type arguments from the target type when there is one.
varremoves the target type. - Without a target and without helpful arguments, the type argument becomes its bound, usually
Object. - Arguments help only when their types are connected to the type parameter.
- The variable type is the concrete class of the initializer, not an interface.
- Add the type argument explicitly on the right side whenever you use
varwithnew.
Exercise
What are the inferred types of var a = new ArrayList<>(List.of("x")); and var b = new ArrayList<>(5);? Which one accepts b.add(3.14), and why?
Show answer
a is ArrayList<String>, because the constructor argument is a List<String> that fixes the element type. b is ArrayList<Object>, because the argument 5 is the initial capacity and says nothing about the element type. So b.add(3.14) compiles (the double is boxed to Double, which is an Object), while a.add(3.14) does not.
Exercise
A teammate writes var users = new ArrayList<>(); and later calls users.add(new User("Ada")); followed by String n = users.get(0).getName();. Explain why the last line fails to compile and give two different ways to fix the declaration.
Show answer
With var and no target type or arguments, users is ArrayList<Object>, so users.get(0) returns Object, which has no getName() method. One fix is var users = new ArrayList<User>();, which gives ArrayList<User>. The other is List<User> users = new ArrayList<>();, which gives List<User> and lets the diamond infer User from the target type.
Exercise
Given var items = new ArrayList<String>();, why does items = new LinkedList<>(); fail, and what declaration would allow it?
Show answer
The variable type is ArrayList<String>, the concrete class of the initializer, and a LinkedList is not an ArrayList. Declaring List<String> items = new ArrayList<>(); makes the variable type List<String>, so any List implementation can be assigned later.