调用具有两个不同通用参数的通用函数仍然编译 [英] Calling generic function with two different generic arguments still compiles

查看:93
本文介绍了调用具有两个不同通用参数的通用函数仍然编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码甚至可能编译?就我可以看到计数函数调用两种不同的类型,但编译器不抱怨和愉快地编译此代码。

How is it possible that following code even compiles? As far as I can see the count function is called with two different types, yet compiler doesn't complain and happily compiles this code.

public class Test {
        public static <T> int count(T[] x,T y){
                int count = 0;
                for(int i=0; i < x.length; i++){
                        if(x[i] == y) count ++;
                }
                return count;  
        }
        public static void main(String[] args) {
                Integer [] data = {1,2,3,1,4};
                String value = "1";
                int r =count(data,value);
                System.out.println( r + " - " + value);
        }
}


推荐答案

这种情况下 T 是无用的。您可以将签名更改为 public static int count(Object [] x,Object y),而不会对编译器允许它接受的任何参数有任何影响。 (您可以看到 Arrays.fill()的签名用作签名。)

In this case the T is useless. You can change the signature to public static int count(Object[] x, Object y) without any effect on what arguments the compiler will let it accept. (You can see that the signature for Arrays.fill() uses that as the signature.)

如果我们考虑更简单的情况,其中你只有类型 T 的参数,你可以看到,因为任何 T 也是它的超类的一个实例, T 总是可以推断为它的上界,它仍然接受与以前相同的参数类型。因此,我们可以删除 T 并使用其上限(在这种情况下 Object )。

If we consider the simpler case, where you just have arguments of type T, you can see that, since any instance of T is also an instance of its superclasses, T can always to be inferred to be its upper bound, and it will still accept the same argument types as before. Thus we can get rid of T and use its upper bound (in this case Object) instead.

Java中的数组以相同的方式工作:数组是协变的,这意味着如果 S T S [] T [] 的子类。所以同样的参数适用 - 如果你只是有参数类型 T T [] ,<$

Arrays in Java work the same way: arrays are covariant, which means that if S is a subclass of T, S[] is a subclass of T[]. So the same argument as above applies -- if you just have arguments of type T and T[], T can be replaced by its upper bound.

(请注意,这不适用于不是协变的通用类型或逆向: List< S> 不是 List< T> 的子类型。)

(Note that this does not apply to generic types, which are not covariant or contravariant: List<S> is not a subtype of List<T>.)

这篇关于调用具有两个不同通用参数的通用函数仍然编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆