gpt4 book ai didi

Java方法参数给出编译错误 "Unexpected bound"

转载 作者:行者123 更新时间:2023-11-30 07:41:19 29 4
gpt4 key购买 nike

在这 2 个方法中,inspect1 显示编译错误“Unexpected bound”而 inspect2 工作正常,为什么?

public <U> void inspect1(List<U extends Number> u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}

public <U> void inspect2(List<? extends Number> u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}

最佳答案

要让它工作,这应该在泛型类型方法签名中定义,说明 U 可以是任何类型,它是 Number 的子类:

public <U extends Number> void inspect1(List<U> u) {
// body
}

此外,请注意在第二种方法中,参数 U 从未使用过,应该如下所示。这表示接受 Number 的子类的任何列表。不涉及通用参数 U

public void inspect2(List<? extends Number> u) {
// body
}

Is there going to be any difference between these 2 methods (inspect1 and inspect2) you have provided in the answer, or they are going to work exactly the same?

它们实际上做同样的事情,因为你不能扩展 Number 并且扩展这个类的唯一类型是(希望我得到它们):

  • DoubleFloatShortIntegerLong

关于Java方法参数给出编译错误 "Unexpected bound",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56174340/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com