javalistarraylist

Question about Lists and ArrayLists and more specifically about casting


Why first three lines didn't compile and the remaining 2 did? How exactly does this work?

import java.util.*;
class HelloWorld {
    public static void main(String[] args) {
        //List<Number> ints = new ArrayList<Integer>(); DIDN'T compile
        //List<Integer> nums = new ArrayList<Number>(); DIDN'T compile
        //List<Object>nums = new ArrayList<Integer>();  DIDN'T compile
        //List<? extends Number> nums = new ArrayList<Integer>(); compiled
        //List<? super Number> nums = new  ArrayList<Object>(); compiled
    }
}`

Solution

  • First 3 line was not compiled because in Java, generic types are not satisfied or covariant fro ensuring type safety which means that List<Intreger> is not count a sub type of List<Number>. lets describe line of given code

    Don't Compile Line :

    Compiled Line :