0

I've been working on basic Java programs for classes, however, I like to look ahead and learn new things independent of the class.

While I was looking at ArrayLists in Java, I noticed that I could do the following, and both seem to work,

ArrayList<String> var = new ArrayList<String>();

While the following also runs, without my IDE giving any warnings or errors,

ArrayList<String> var1 = new ArrayList<>();

Thus I am confused as to why the second set of chevrons exist, it doesn't seem to make a difference in the code.

Any and all help is appreciated!

Raj
  • 21
  • 8
  • Java 7 introduced the diamond operator (<>) to reduce the verbosity of generics code. For instance, instead of having to declare a List's type in both its declaration and its constructor, you can now simplify the constructor declaration with <>, and the compiler will infer the type. – SSK Mar 15 '20 at 04:48
  • Please find detailed answer here: https://stackoverflow.com/questions/4166966/what-is-the-point-of-the-diamond-operator-in-java-7 – Tarun Mar 15 '20 at 04:52
  • Thanks so much for letting me know. I had no idea, and I'm glad to find out! :) – Raj Mar 15 '20 at 04:57
  • Depending on your IDE and how it's configured, you may actually get a mild suggestion to use the diamond instead of repeating the generic type parameters in your `new` expression. – Kevin Anderson Mar 15 '20 at 05:17

0 Answers0