如何使Java通用方法静态? [英] How to make a Java Generic method static?
问题描述
以下是关于如何使Java泛型类将单个项目附加到数组的一段代码。我怎样才能让appendToArray成为一个静态方法。
public class ArrayUtils< E> {
public E [] appendToArray(E [] array,E item){
E [] result =(E [])new Object [array.length + 1];
结果[array.length] = item;
返回结果;
}
}
只能将签名更改为
public static< E> E [] appendToArray(E [] array,E item)
重要细节: 返回值前面的泛型表达式总是引入(声明)一个新的泛型变量。 另外,类型变量( 那么,这是什么意思: 为了更好地反映这个事实,更正确的答案是: 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.
the only thing you can do is to change your signature to Important details: Generic expressions preceding the return value always introduce (declare) a new generic type variable. Additionally, type variables between types ( So, what does this mean:
In my answer To reflect this fact better, a more correct answer would be:
这篇关于如何使Java通用方法静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
ArrayUtils
)和静态方法( appendToArray
)永远不会相互干扰。
在我的回答< E>
中会隐藏 static ,则从
AND ArrayUtils< E>
> E < E>
与 ArrayUtils< E>无关
E
/ code>。
public static< I> I [] appendToArray(I [] array,I item)
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;
}
}
public static <E> E[] appendToArray(E[] array, E item)
ArrayUtils
) and static methods (appendToArray
) never interfere with each other.<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>
.public static <I> I[] appendToArray(I[] array, I item)