Creating ArrayList with Type Arguments
What you'll learn: How to instantiate an ArrayList with a specific type argument to create type-safe collections.
The Core Idea
Now that you understand ArrayList<E> is a generic collection, it's time to actually create instances of it. When you instantiate an ArrayList, you specify what type of objects it will hold by providing a type argument in angle brackets. This turns the generic blueprint into a concrete, type-safe collection.
Basic Syntax
Here's how you create ArrayList instances with specific types:
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> scores = new ArrayList<Integer>();
The first line creates an ArrayList that can only hold String objects. The second creates one that holds Integer objects (remember: type arguments cannot be primitives, so we use the wrapper class).
The Diamond Operator
Java provides a shorthand called the diamond operator (<>) that lets the compiler infer the type argument from the left side:
ArrayList<String> names = new ArrayList<>(); // Cleaner!
ArrayList<Integer> scores = new ArrayList<>();
The empty <> tells the compiler "use the same type I declared on the left." This reduces repetition and is the preferred modern style.
Why This Matters
Without type arguments, you'd get a raw type that accepts any object, losing type safety. With type arguments, the compiler enforces that only the correct type goes in, and you get that exact type back out—no casting needed.
Key Takeaway: Use ArrayList<TypeName> with the diamond operator (<>) on the right side to create type-safe collections that hold only the specified type of object.