I have two questions
1.Is there any difference between below two declarations.?
(case i)
List<String> li = new ArrayList();
(case ii)
List<String> li = new ArrayList<String>();
2.I know that generics benefits is Stronger type checks at compile time.
Then why we need to declare like in case ii ?
Since Object creation is at runtime only declaration at compile time.
There's no difference in the code that's executed - but the first form will generate a warning. If you don't have linting enabled for generics, you're likely to get a message like this:
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
With the suggested flag, you'll get something like this:
Test.java:6: warning: [unchecked] unchecked conversion
List<String> li = new ArrayList();
^
required: List<String>
found: ArrayList
1 warning
The reason for the warning is that it's sort of not as safe - you're using an expression of a raw type (new ArrayList()) as the value to assign to a variable of type List<String>. The compiler doesn't know whether this raw type value was actually originally created to hold other vaues. For example:
List numbers = new ArrayList(); // Raw types on both sides
numbers.add(Integer.valueOf(10));
List<String> li = numbers;
String first = li.get(0);
Or even:
List<Integer> numbers = new ArrayList<Numbers>();
numbers.add(Integer.valueOf(10));
List raw = numbers;
List<String> li = raw;
String first = li.get(0);
In both of these cases, we'll end up with an exception when we get to the last line... whereas if we were using the generic type for all expressions, it wouldn't even compile:
List<Integer> numbers = new ArrayList<Numbers>();
numbers.add(Integer.valueOf(10));
List<String> li = numbers; // Compile-time error
String first = li.get(0);
Raw types are only present for backward compatibility, and should be avoided wherever possible.
See the Java generics FAQ for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With