Search code examples
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 :

    • List<Number> ints = new ArrayList<Integer>(); : We can not assign a List<Integer> to a variable type of List<Number> because generics in java are not covariant.
    • List<Integer> nums = new ArrayList<Number>(); : Same reason as first one ,we can't assign List<Number> to a variable type of List<Integer>
    • List<Object>nums = new ArrayList<Integer>(); : Same reason as first one ,we can't assign List<Integer> to a variable type of List<Object>

    Compiled Line :

    • List<? extends Number> nums = new ArrayList(); : This line work because in this line you use a wildcard with a upper bound ? extends Number. Upper bound wildcard allows you to accept any subtype of type T. That mean ? extends Number this accept Integer, Double, Float etc.

    • List<? super Number> nums = new ArrayList(); :

    • List<? extends Number> nums = new ArrayList(); : This line work because in this line you use a wildcard with a lower bound ? extends Number.Lower bound wildcard allows you to accept any super type of type T. That mean ? extends Number this accept Number and Object.