2

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));
Pieter
  • 69
  • 1
  • 2
  • 2
    Does this answer your question? [Diamond operator in raw type context](https://stackoverflow.com/questions/36363062/diamond-operator-in-raw-type-context) – OH GOD SPIDERS Aug 20 '21 at 11:41
  • Just as a general note, in case it wasnt clear: Never leave out the `<...>` on a generic type, just writing `List balloons` gives you a raw-type. Thats basically a fallback mode for pre Java 5 and is even worse than `List`, you lose all type safety. – Zabuzard Aug 20 '21 at 11:44

1 Answers1

2

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>

Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • 1
    As a note, `List` and `List` are similar but different. They behave differently. For example you can do `balloons = dogs;` with raw types on the variable. RIP type safety. – Zabuzard Aug 20 '21 at 11:45
  • 1
    @Zabuzard Thank you for pointing that out. Added a link in the question that explains the difference between both types. – Yousaf Aug 20 '21 at 11:53