I am practicing Java Generics trying to understand raw types vs generic types.
I have created a raw list and added a String element. I have also created an Integer list added an Integer to it. Now I have assigned the raw list to the Integer list (integerList = rawList; - It just throws a warning message). Now in the Integer list, I have a String element and able to print it. I am not able to add new String elements to Integer list as compiler checks during compilation.
But by assigning a raw list which contains a String (or any other type) we are able to store a String (or any other type) in an Integer list. Don't you think it's a bug in Java?
I tried searching google and stackoverflow to find out an answer for this but didn't get any solution for this.
package generics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GenericBox<T> {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<>(Arrays.asList(1,2,3,4));
List rawList = new ArrayList();
rawList.add("Subbu");
integerList = rawList;
integerList.add(5);
System.out.println(integerList);
System.out.println(integerList.get(0));
System.out.println(integerList.get(1));
}
}
Result:
[Subbu, 5]
Subbu
5
I don't expect String to be stored in an Integer list and feel it like a bug in java. What do you think?
Thank you, Subbu.