0

What is the difference between List <String> list = new ArrayList<>(); vs List <String> list = new ArrayList<String>();

static void first(){
    List <String> list = new ArrayList<>();
    list.add("hello world");
    String s = list.get(0);

static void second(){
    List <String> list = new ArrayList<String>();
    list.add("hello world");
    String s = list.get(0);

Edit 1: This question intends the need to clarify the difference of using String in diamond operator in the "second" method and how it is different from "first" method where String is absent from the diamond operator. Why explicitly mention String in the diamond operator if the method works without stating it? My question has nothing to do with diamond operator, it's about what's inside those operators.

Edit 2: This question is not about diamond operators.

learn_java
  • 31
  • 4
  • @chrylis Can you please explain how this question is the duplicate of the one that you mentioned? In my understanding, this question is about using or not using String inside the diamond operator. – learn_java Feb 25 '17 at 04:08
  • the first syntax is just a sugar added in Java 7 to reduce typing and the linked question describes this feature. You might also look at the http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html. The short answer is: the second example is just old syntax left for backward compatibility and some edge cases. – SergGr Feb 25 '17 at 04:15
  • @SergGr I guess it won't answer my question still. An answer would be that both are same or some explanation on why they are different. I am not concerned about the diamond operator, rather why mention String in the second method within the diamond operator? – learn_java Feb 25 '17 at 04:21
  • 1
    The *only* difference between these snippets is the use of the diamond operator instead of explicitly providing the generic type. – chrylis -cautiouslyoptimistic- Feb 25 '17 at 04:26
  • @chrylis I guess I should have mentioned the right-hand side of the assignment. i.e. "= new ArrayList<>();" vs "=new ArrayList();". – learn_java Feb 25 '17 at 04:28
  • 1
    The answer gets too long for a comment. Strictly speaking `ArrayList` and `List` specify type names while `ArrayList<>` (out of context) doesn't. And generally `ArrayList` is not compatible with `List` if `TypeA` is different from `TypeB` (but see also variance). Thus historically you had to specify parameters for all generics on both sides of such an assignment. In Java 7 compiler developers added a feature that in simple cases compiler might infer generic type parameters on the right side by the type expected on left side and thus diamond operator was born. – SergGr Feb 25 '17 at 04:33
  • @SergGr Now this is what I was looking for. Thank you for your patience. – learn_java Feb 25 '17 at 04:37

0 Answers0