简体   繁体   English

Java中的上边界通配符

[英]Upper Bounded wildcards in Java

I have two generic methods that calculate the sum of elements of a List. 我有两个通用的方法来计算List的元素总和。 The signatures of the methods are 方法的签名是

  1. double method1(List<? extends Number> list) - Here I am using a wildcard. double method1(List<? extends Number> list) - 这里我使用的是通配符。

  2. <U extends Number> double sumOfList1(List<U> list) - Here there is a name for type parameter. <U extends Number> double sumOfList1(List<U> list) - 这里有一个type参数的名称。

Is there any difference between these two or they're same in terms of functionality ? 这两者之间有什么区别,或者它们在功能方面是否相同? Using a type parameter name instead of wildcard has any advantages ? 使用类型参数名称而不是通配符有什么优势?

public static double sumOfList(List<? extends Number> list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}

 public static <U extends Number> double sumOfList1(List<U> list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}

Thank you. 谢谢。

There is absolutely no difference, the purpose of declaring U is so that you can use it: 绝对没有区别,声明U的目的是让你可以使用它:

public static <U extends Number> void doSomething(List<U> list, Consumer<U> sink) {
    list.forEach(sink::accept)
}

This means that you don't care what U is, but it must extend from Number . 这意味着你不关心U什么 ,但它必须从Number扩展。 What you do care about is that the List contains a type that is compatible with what the Consumer can accept. 您关心的是List包含的类型与Consumer可以接受的类型兼容。


Alternatively you can use U inside the method to declare new instances of the generic type: 或者,您可以在方法内使用U来声明泛型类型的新实例:

public static <U extends Number> List<U> copy(List<U> list) {
    List<U> copy = new ArrayList<>();
    copy.addAll(list)
    return copy;
}

yes, I know, there are neater ways to do this - please treat it as an illustrative example 是的,我知道,有更简洁的方法可以做到这一点 - 请将其视为一个说明性的例子

由于您没有在此方法中使用U ,因此它们没有区别。

Because of type erasure the code being executed in the end is the same so there is no difference using one over the other. 由于类型擦除,最终执行的代码是相同的,因此使用一个而不是另一个没有区别。

Type erasure is explained in this site like: 类型擦除在本网站中解释如下:

The process of enforcing type constraints only at compile time and discarding the element type information at runtime. 仅在编译时强制执行类型约束并在运行时丢弃元素类型信息的过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM