1

I know why I am getting the warning(i.e assigning raw type to parameterized type), but I don't exactly get what will be possible sequences if I ignore the warning.

List list = new ArrayList();           
List<Integer> iList = list;     // warning: unchecked conversion
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25

3 Answers3

2

You get ClassCastException at runtime. Casts generated by the compiler could fail at runtime. This will violate the fundamental guarantee provided by the generic type system. Literally your code is not type safe. Check this out.

List list = new ArrayList();           
List<Integer> iList = list;
list.add("wrong");
for (Integer integer : iList) {
    System.out.println(integer);
}

Here's the error you get at runtime.

java.lang.String cannot be cast to java.lang.Integer

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
1

Ignoring the warning may result in ClassCastException if you expect the List to contain elements of one type and it contains elements of an unrelated type.

For example, the following will pass compilation (with a warning) and will throw ClassCastException in runtime:

List list = new ArrayList();    
list.add("something");       
List<Integer> iList = list;
Integer i = iList.get(0);
Eran
  • 387,369
  • 54
  • 702
  • 768
1

The (only) runtime consequence is code failing due to ClassCastException's, either directly or indirectly1.

The other consequence is that you allow errors that should be detected and corrected at compile time to proceed into test, and maybe production where the costs and consequences may be significantly worse.

While ignoring these warnings is a bad idea, suppressing them incorrectly can be worse.

what do you mean by suppressing them incorrectly ?

I mean adding a @SuppressWarning annotation for a warning that actually will result in a runtime exception or another (real) problem. Adding a @SuppressWarning annotation just to make the compiler "shut up" is a dangerous habit.


1 - For instance, if you caught and incorrectly squashed a ClassCastException!

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216