Search⌘ K
AI Features

The Get & the Put Principle

Explore the Get and Put principle in Java generics to understand why you cannot add elements to a list declared with an 'extends' wildcard. Learn how type safety is maintained with bounded wildcards and why such lists are typically used as method parameters rather than as internal variables.

We'll cover the following...
1.

What is the Get and Put principle?

Show Answer
Did you find this helpful?
Technical Quiz
1.

Consider the code snippet below. This time we are saving a Number into a list of types that extends Number. Will this work?

    void addNumber(Number num) {
        List<? extends Number> listOfNumbers = new ArrayList<>();
        listOfNumbers.add(num); // Will this work?
    }
A.

Compiles

B.

Doesn’t compile

C.

Compiles with a checked warning and throws a runtime ClassCastException


1 / 1

The above code will never compile because we are trying to add a number into a list of a type that extends Number and we can't guarantee the type of the number being passed into the method. Actually, the way the code is written, it is pretty useless. The list can never be added to since it is being declared inside the method and new-ed up at the same time.

Usually, list with unbounded wildcard or an extends wildcard bound are used to declare the parameter types in the method signature and not as variables inside a method.

Note that List<? extends Number> does not mean list of objects of different types, all of which extend Number. Rather it implies list of objects of a single type which extends Number.

1.

Can we consider List<?> as an immutable list since we can never add to this list?

Show Answer
1 / 2
Java
import java.util.*;
class Demonstration {
public static void main( String args[] ) {
List<? super Number> listOfNumbers = new ArrayList<>();
Integer i = Integer.valueOf(5);
Double d = Double.valueOf(5);
// Adding an integer
listOfNumbers.add(i); // Allowed
// Adding a double
listOfNumbers.add(d); // Allowed
// i = listOfNumbers.get(0); // <--- Compile time error
Object object = listOfNumbers.get(0); // Allowed
}
}
1.

What to do when we want to both get and put values in a structure?

Show Answer
Did you find this helpful?