0

What are the implications of this:

List<String> a = new ArrayList();

When I say "implications", I mean, for using it in various scenarios, for example, passing to a function that expects a List, or a List, modifying the list, retrieving from the list, etc. I ask because to my mind the reference is what we "pass around" to do things with, and the reference is typed (as List<String>); but the compiler will complain about "unchecked or unsafe operations".

Thank you.

Edit: Thank you for pointing out the (possible) duplicate, but the answer given is unsatisfactory and merely reinforces my point:

Stack s = new Stack() This will result in an "unchecked conversion" warning, because it's not safe in general to convert a raw type to a parameterized type. However, it's perfectly safe to do so in this case: pushing Integer values will not cause any errors; pushing non-Integer values will cause a type error.

I am asking, why is the compiler saying this is unsafe, when all we do is pass around and call methods on and with references, and the reference is typed. If I have a method foo(List) or foo(List<String>) and I want to call foo with my ArrayList, I will pass the reference a, not the object, and the reference is typed. So, what is the compiler complaining about exactly and why?

JL_SO
  • 1,742
  • 1
  • 25
  • 38
  • it will complain on new ArrayList() it should be new ArrayList<>() to allow type inference. – JEY Jul 05 '18 at 15:43
  • The compiler's required to give a warning any time you make an unchecked conversion like that regardless of the possible ramifications of the particular assignment. Also see https://stackoverflow.com/a/22203300/2891664 – Radiodef Jul 06 '18 at 01:17

0 Answers0