扩展Object []为泛型类型

时间:2019-07-04 06:35:37

标签: java

我正在尝试定义一个通用方法,该方法可以打印对象类型的数组。我编写了以下代码:

class ArrayPrinter
{
    public <T extends Object[]> void printArray(T t) {
        for(Object o: t) {
            System.out.println(o);
        }
    }  
}
public class javaGenerics {
    public static void main(String args[]) {
        ArrayPrinter myArrayPrinter = new ArrayPrinter();
        Integer[] intArray = {1, 2, 3};
        String[] stringArray = {"Hello", "World"};
        myArrayPrinter.printArray(intArray);
        myArrayPrinter.printArray(stringArray); 
    }
}

但是它不起作用,并引发以下错误:

javaGenerics.java:7: error: unexpected type
    public <T extends Object[]> void printArray(T t) {
                            ^
  required: class
  found:    Object[]
1 error

我可以从错误中了解到我提供了一个类名。但是我不知道对象数组的类名是什么。

5 个答案:

答案 0 :(得分:3)

我将printArray更改为

public <T extends Object> void printArray(T[] t) {
    for(Object o: t) {
        System.out.println(o);
    }
}  

这就是让T扩展Object而不是Object数组,并使其成为T的数组。

实际上,根本不需要扩展Object,因为type参数始终是非原始类型

public <T> void printArray(T[] t) {
    for(Object o: t) {
        System.out.println(o);
    }
}

答案 1 :(得分:2)

public <T>  void printArray(T[] t) {
        for (Object o : t) {
            System.out.println(o);
        }
    }

应该是正确的方法。

代替

public <T extends Object[]> void printArray(T t) {
        for(Object o: t) {
            System.out.println(o);
        }
    }  

答案 2 :(得分:2)

这里不需要泛型:

public void printArray(Object[] t) {
    for(Object o: t) {
        System.out.println(o);
    }
}

这将很好地工作,因为Java数组是协变的。

答案 3 :(得分:0)

我将在下面的解释中添加其他答案。

Array是一个Object,但是它没有类,也没有键入自身。您可以扩展类,但不能扩展数组,也不能扩展Java中的任何其他对象组。任何对象组都不能具有确定的类定义。 数组是一种在内存中保留 N个指针的方法,用于指定对多个对象的引用(如果有对象或) >对于基元。因此,从数组扩展是未定义的。

答案 4 :(得分:0)

我假设您正在尝试创建一种接受任何类型的对象数组的方法。在这种情况下,您可以使用以下内容。

public <T> void printArray(T[] array) {
        for(T t: array) {
            System.out.println(t.toString());
        }
    }

在这种情况下,因为实际上并没有使用T类型,所以实际上可以这样做:

    public  void printArray(Object[] array) {
        for(Object o: array) {
            System.out.println(o.toString());
        }
    }

如果您真的想扩展数组类本身,事实证明您做不到:https://www.quora.com/Why-cant-the-array-class-in-Java-be-extended

相关问题