Tag: extends

Java Generics extends

If you pass Long and/or Integer to a method then signature of the method is void m(Number n)
If you pass List and/or List to a method then signature of the method is void m(List<? extends Number> numbers) otherwise compilation error of incompatible types.

package com.bawi;

import java.util.ArrayList;
import java.util.List;

public class TestExtendsGenerics {

    public static void main(String[] args) {
        int i = 1;
        List<Integer> ints = new ArrayList<>();
        ints.add(i);

        long l = 1L;
        List<Long> longs = new ArrayList<>();
        longs.add(l);

        printNumber(i);

        // Error: incompatible types: 
        // java.util.List<java.lang.Integer> cannot be converted to java.util.List<java.lang.Number>
        //printNumberList(ints);
        
        printExtendsNumberList(ints);


        printNumber(l);

        // Error: incompatible types: 
        // java.util.List<java.lang.Long> cannot be converted to java.util.List<java.lang.Number>
        //printNumberList(longs);
        
        printExtendsNumberList(longs);
    }
    private static void printNumber(Number number) {
        System.out.println(number);
    }

    private static void printNumberList(List<Number> numbers) {
        System.out.println(numbers);
    }

    private static void printExtendsNumberList(List<? extends Number> numbers) {
        System.out.println(numbers);
    }
}