This list is declared to hold strings. Adding hello is fine. Adding forty two isn't. Run it. Java refuses to compile. The list only accepts strings.
Main.javajava
import java.util.ArrayList;public class Main { public static void main(String[] args) { ArrayList<String> words = new ArrayList<>(); words.add("hello"); words.add(42); }}
Output
Main.java:6: error: incompatible types: int cannot be converted to String
words.add(42);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full
output
1 error
error: compilation failed
Box, angle T, angle, is a generic class. T is a placeholder for a type. Whoever uses Box decides what T is. And get returns T, so no casting is ever needed.
Main.javajava
public class Box<T> { private T item; public void put(T item) { this.item = item; } public T get() { return item; }}
A box of strings, and a box of integers, from the same class. Get gives back the right type each time. So we can call to upper case on one, and multiply the other. Run it. Remember the milk, in capitals, and forty two.
Main.javajava
public class Main { public static void main(String[] args) { Box<String> note = new Box<>(); note.put("Remember the milk"); Box<Integer> number = new Box<>(); number.put(7); String s = note.get(); int n = number.get(); System.out.println(s.toUpperCase() + " " + (n * 6)); }}
Output
REMEMBER THE MILK 42
Also uses Box.java
public class Box<T> { private T item; public void put(T item) { this.item = item; } public T get() { return item; }}
Generics put a type in angle brackets, so Java knows what a list or class holds. Mistakes are caught before running. Next, why lists of numbers say Integer.