如何使 Java 通用方法静态化? [英] How to make a Java Generic method static?

查看:32
本文介绍了如何使 Java 通用方法静态化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是关于如何制作 java 泛型类以将单个项目附加到数组的片段.如何使 appendToArray 成为静态方法.向方法签名中添加静态会导致编译错误.

The following is a snippet on how to make a java generic class to append a single item to an array. How can I make appendToArray a static method. Adding static to the method signature results in compile errors.

public class ArrayUtils<E> {

        public E[] appendToArray(E[] array, E item) {
            E[] result = (E[])new Object[array.length+1];
            result[array.length] = item;
            return result;
        }
}

推荐答案

你唯一能做的就是把你的签名改成

the only thing you can do is to change your signature to

public static <E> E[] appendToArray(E[] array, E item)

重要细节:

返回值之前的泛型表达式总是引入(声明)一个新的泛型类型变量.

Generic expressions preceding the return value always introduce (declare) a new generic type variable.

此外,类型 (ArrayUtils) 和静态方法 (appendToArray) 之间的类型变量永远不会相互干扰.

Additionally, type variables between types (ArrayUtils) and static methods (appendToArray) never interfere with each other.

那么,这是什么意思:在我的回答中,如果方法不是 static 会从 ArrayUtils 中隐藏 E代码>.AND ArrayUtils 中的 E 无关.

So, what does this mean: In my answer <E> would hide the E from ArrayUtils<E> if the method wouldn't be static. AND <E> has nothing to do with the E from ArrayUtils<E>.

为了更好地反映这一事实,更正确的答案是:

To reflect this fact better, a more correct answer would be:

public static <I> I[] appendToArray(I[] array, I item)

这篇关于如何使 Java 通用方法静态化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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