0

I am creating an object of ArrayAdapter in Java(Android Studio) is it required to add String Data type to both sides inside the diamond operators? can anyone explain

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<"here">(this,android.R.layout.simple_list_item_1,numbersInChars);
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Sarwar Sateer
  • 395
  • 3
  • 16
  • No it is not needed! – Harmandeep Singh Kalsi Jun 30 '20 at 10:57
  • Thanks for your response. what happens if we add String to that too? if possible share me some info if it is not required why there is still <> there. – Sarwar Sateer Jun 30 '20 at 11:01
  • It was requiered pre java 7, now the compiler can infer the type from what you defined on the left side. You have to put the diamond operato on the right side because you are using generics, without it java would use the raw type. Read more here https://stackoverflow.com/questions/4166966/what-is-the-point-of-the-diamond-operator-in-java-7 – MissingSemiColon Jun 30 '20 at 11:05

2 Answers2

1

No, you do not need to specify it on the right side. However, it won't cause any harm if you specify there. Please read more about the diamond at https://docs.oracle.com/javase/tutorial/java/generics/types.html. Given below is an example from the same page:

Box<Integer> integerBox = new Box<>();

As you can see Integer has not been specified on the right side. However, if you wish, you can write it as follows as well:

Box<Integer> integerBox = new Box<Integer>();
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

The java generics tutorial contains the following explanation about the diamond operator that answers your question:

In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context.

The compiler can determine the String type argument to invoke the constructor because you specified it in the left part of your assignment ArrayAdapter<String> arrayAdapter = ..., so there is no need to specify it.

dariosicily
  • 4,239
  • 2
  • 11
  • 17