Reputation: 89
Why is it that Java accept below line of code, with <> only being present on the right? The <> signs have no (generics functionality) purpose like this?
List balloons = new ArrayList<>();
So far I only understand the use of <> on the right as shown in below example. Here Java infers the type on the left, so there's no need to specify again on the right and simply <> can be used.
List<String> balloons = new ArrayList<>();
balloons.add("blue");
balloons.add("yellow");
// balloons.add(1); // will not compile as balloons is type safe, demanding String input
System.out.println(balloons.get(0));
System.out.println(balloons.get(1));
// System.out.println(balloons.get(2));
Upvotes: 2
Views: 62
Reputation: 29334
List defined as
List balloons = new ArrayList<>();
is a raw type, which means you can store anything in this list.
This
List balloons = new ArrayList<>();
is similar to
List<Object> balloons = new ArrayList<>();
Note: Its important to note that List
and List<Object>
are similar BUT there are differences between them. See: Java difference between List and List<Object>
Upvotes: 2