Command Palette

Search for a command to run...

Back to the lesson: Topic 8.1 — Why Generics Exist
Core Java · Example 3 of 4

A box for Object versus a generic box

One generic class, Box<T>, serves every type safely. You'll write classes like this in Topic 8.2.

Generics let a class or method work with many types while the compiler still checks which type you used. List<String> is a list the compiler knows holds only strings, so wrong elements become compile errors and the casts disappear.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a program that stores three city names in a List<String>, then prints the total number of characters, without any casts.

02

Write a Map<String, Integer> word counter for the words {"tea", "chai", "tea", "coffee", "tea"}, using a TreeMap so the output order is fixed, and print the map.

03

Write a generic-free ObjectPair class holding two Objects, then a generic Pair<A, B>. Store ("Asha", 92) in each and print the name length and the mark plus 1, showing where casts are needed.

Explain it without notes

01

What problem did generics solve? Describe how the same bug behaves with and without them.

02

What is the difference between a type parameter and a type argument?

03

Why can't you write List<int>, and what happens when you add an int to a List<Integer>?

04

What is a raw type, why does Java still allow it, and why should you avoid it?

A box for Object versus a generic box
Sign in to run this example in your browser.

Expected output

ObjectBox: tea
Box<String>: 4 letters
Box<Integer>: 42