Java 不应该';addToCollection(t[]a,Collection<;t>;c)中的类型t是否相同?

Java 不应该';addToCollection(t[]a,Collection<;t>;c)中的类型t是否相同?,java,generics,collections,Java,Generics,Collections,我不明白为什么下面的代码可以工作: import java.util.ArrayList; import java.util.Collection; public class Main { public static void main(String[] args) { Integer[] arr=new Integer[]{1,2,3}; ArrayList<Object> al=new ArrayList

我不明白为什么下面的代码可以工作:

import java.util.ArrayList;
import java.util.Collection;

    public class Main {

        public static void main(String[] args) {
            Integer[] arr=new Integer[]{1,2,3};
            ArrayList<Object> al=new ArrayList<>();
            addToCollection(arr, al);
        }
        static <T> void addToCollection(T[] a, Collection<T> c)
        {
            for(T o:a)
                c.add(o);
        }
    }
import java.util.ArrayList;
导入java.util.Collection;
公共班机{
公共静态void main(字符串[]args){
整数[]arr=新整数[]{1,2,3};
ArrayList al=新的ArrayList();
addToCollection(arr,al);
}
静态void addToCollection(T[]a,集合c)
{
对于(TO:a)
c、 添加(o);
}
}
难道不是:


static void addToCollection(T[]a,Collection这两个
arr
al
都是对象的子类型,所以这就是您得到的。如果将
addToCollection
函数更改为返回类型,则会发生以下情况:

public static class Main {

    public static void main(String[] args) {
        Integer[] arr=new Integer[]{1,2,3};
        ArrayList<Object> al=new ArrayList<>();
        Collection<Object> objects = addToCollection(arr, al);  // Compiles
        Collection<Integer> numbers = addToCollection(arr, al); // Doesn't compile
    }

    static <T> Collection<T> addToCollection(T[] a, Collection<T> c)
    {
        for(T o:a) // Behold the side effect
            c.add(o);

        return c;
    }
}
公共静态类Main{
公共静态void main(字符串[]args){
整数[]arr=新整数[]{1,2,3};
ArrayList al=新的ArrayList();
Collection objects=addToCollection(arr,al);//编译
集合编号=addToCollection(arr,al);//不编译
}
静态集合addToCollection(T[]a,集合c)
{
for(to:a)//看看副作用
c、 添加(o);
返回c;
}
}

与什么相同?如果你有一组
自行车
,你难道不能将其添加到
车辆
集合中吗?他问为什么允许他通过
数组列表
整数[]
。问题是为
T
推断哪种类型,我相信它是
Object
,但目前没有对JLS的特定引用。arr是一个对象[](因为Integer[]是一个对象[]),而ArrayList是一个集合,因此可以编译。请注意
Object[]x=new Integer[10];
可以编译,但
ArrayList l=new ArrayList();
不能编译。因此,第二个
addToCollection(arr,al)
返回一个
集合,对吗?是的,它不会编译,因为类型不正确。它只是显示它。
public static class Main {

    public static void main(String[] args) {
        Integer[] arr=new Integer[]{1,2,3};
        ArrayList<Object> al=new ArrayList<>();
        Collection<Object> objects = addToCollection(arr, al);  // Compiles
        Collection<Integer> numbers = addToCollection(arr, al); // Doesn't compile
    }

    static <T> Collection<T> addToCollection(T[] a, Collection<T> c)
    {
        for(T o:a) // Behold the side effect
            c.add(o);

        return c;
    }
}