Can List < Integer > be passed to List < Number > ?

Refer to the Array Covariance article to understand this concept better. Hope you have gone through it, if not please have a look at it. As we know, we can pass a Subtype array to a Supertype array. Ex: We can pass an Integer array to a Number array but can it happen with Generics?

The answer is NO.

After compilation completes the compiler removes the type information. List<String> will be converted to List. This functionality is called Type Erasure ( Erasing of type ).

In the Array Covariance example, we have passed the Integer array to the Number array. When we manipulated the Integer array by passing a Long type to it we got an ArrayStoreException because JRE was aware that the array was instantiated with the Integer type.

But when we consider Generics, the Compiler is removing the type information. Now if we are trying to add a Long Type to the List<Number> then JRE will not be aware on List<Integer> was passed to List<Number> since the type information was already removed. Now, this would cause a big issue as our business logic will get totally affected. To avoid such a scenario our Compiler will throw an exception at the very start. Hence a Generic Subtype list cannot be passed to the Supertype list.

Since the JRE is not having any information about the generic type hence Generics are termed as non-reifiable.

public class GenericsCheck {
   public static void main(String[] args) {
      List<Integer> listOfNumbers = new ArrayList<Integer>();
      printNumbers(listOfNumbers);
   }
	
   static void printNumbers(List<Number> numbers) {
      for (Number number : numbers) {
         System.out.println("Element is : "+number);
      }
   }
}

Output : Exception in thread “main” java.lang.Error: Unresolved compilation problem: The method printNumbers(List) in the type GenericsCheck is not applicable for the arguments (List) at GenericsCheck.main(GenericsCheck.java)

Hope you liked the article, if you want to add anything extra please comment below and write to me if I have gone wrong anywhere or if you want to understand any other concept.

Leave a Comment