Student: Ok Professor, you said you’d teach me what the angle brackets in
ArrayList<String> mean.Prof: Those are generics.
ArrayList is one class that can hold any kind of object, so it needs to be told which kind you want for this particular list. The thing in the angle brackets is called the type argument. ArrayList<String> is a list of Strings, and ArrayList<Integer> is a list of Integers.Prof: Look at the types of what comes out.
words.get(0) is a String, and nums.get(0) is an Integer. The type argument decides what get gives back and what add accepts.Student: What stops me from putting the wrong thing in? Like using
add(3) to an ArrayList<String>?Prof: The compiler would stop you. Before your program runs, Java checks every use of
words against the type argument. If you try to add something that isn’t a String, you get a compile error.Prof: This is the same reason
ArrayList<int> didn’t work earlier. A type argument has to be a reference type, like a class or record, not a primitive, so for whole numbers we use Integer. It’s also why you can call words.get(0).length(): the compiler already knows the element is a String.Student:
HashMap had two things in its brackets. Does that work the same way?Prof: Yes, you just give one type argument for each blank, in order. Remember that for a
HashMap<Integer, String> the first is the type of the keys and the second is the type of the values.Prof: When you read the Java documentation, you’ll see these written as
ArrayList<E> and HashMap<K, V>. The letters are placeholders that your type arguments fill in. The E stands for the element type, and K and V for the key and value types. So when the documentation says that get returns an E, for your ArrayList<String> that means a String. You’ll learn how to write classes with placeholders like these in later courses.Practice
Which line creates a list that holds
Strings?ArrayList(String) names = new ArrayList(String)();ArrayList<String> names = new ArrayList<String>();ArrayList names = new ArrayList<String>;String<ArrayList> names = new String<ArrayList>();
Given
ArrayList<Integer> nums = new ArrayList<Integer>();, which of these will not compile?nums.add(7);int first = nums.get(0);nums.add("seven");int count = nums.size();
In
HashMap<String, Integer> ages, what is the type of ages.get("Ada")?StringIntegerHashMapK