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

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

问题描述

以下是关于如何使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)

重要细节:

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



另外,类型变量( ArrayUtils )和静态方法( appendToArray )永远不会相互干扰。



那么,这是什么意思:
在我的回答< E> 中会隐藏 static ,则从 ArrayUtils< E> > E AND < E> ArrayUtils< E>无关 E / code>。



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

  public static< I> I [] appendToArray(I [] array,I 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.

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)

Important details:

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

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

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天全站免登陆