简体   繁体   English

方法返回类型之前的Java泛型有界通配符用法

[英]Java Generics bounded wild card usages before the return type of a method

In the class below, in method m1, is there really any use of mentioning K extends Runnable before the method return type? 在下面的类中,在方法m1中,在方法返回类型之前提及K extends Runnable真的有用吗? I cannot return anything other than Collection<K> anyways. 无论如何,我不能返回Collection<K>以外的任何东西。 And if I want to return any subclass of Runnable I would have specified the method like, 如果我想返回Runnable的任何子类,我会指定类似的方法,

static <T> Collection<? extends Runnable> m1(ArrayList<T> l)

Does the K extends Runnable before the method return type have any significance at all? 在方法返回类型之前, K extends Runnable是否K extends Runnable I get no compilation error for this code either 我也没有此代码的编译错误

public class MainClass {
    public static void main(String[] args) {
        ArrayList<Thread> l = new ArrayList<>();
        l.add(new Thread());
        l.add(new Thread());
        m1(l);
    }

     static <T, K extends Runnable> Collection<K> m1(ArrayList<T> l) {
        ArrayList<K> r = new ArrayList<>();
        return r;
    }
}

By having the parameter K , you can let the caller decide what kind of collection it wants back: 通过使用参数K ,您可以让调用者决定要返回的集合类型:

public class Test {
    static <T, K extends Runnable> Collection<K> m1(ArrayList<T> l) {
        ArrayList<K> r = new ArrayList<>();
        return r;
    }

    static void callingIt(){
        ArrayList<?> list = new ArrayList<>();
        Collection<Thread> threads = m1(list);
        Collection<Runnable> runnables = m1(list);
        Collection<MyTask> special = m1(list);

    }

    class MyTask extends Thread{}
}

If you only had Collection<? extends Runnable> 如果您只有Collection<? extends Runnable> Collection<? extends Runnable> then the caller cannot get back a Collection<Thread> . Collection<? extends Runnable>则调用者无法获取Collection<Thread>

But unless the K is connected to something else, I cannot see how this would work except for empty result lists (because as soon as you want to add something to r , you will have to make sure it is an instance of K ). 但是除非K连接到其他对象,否则我看不到除了空的结果列表外它是如何工作的(因为一旦您想向r添加一些东西,就必须确保它是K的实例)。


You can see this pattern being used in Collections.emptyList : 您可以在Collections.emptyList看到此模式:

public static final List EMPTY_LIST = new EmptyList<>();

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

The method returns the same thing as the field, but because it is a method, the caller can use it to produce generically typed lists of any type (whereas the field cannot be flexible like this). 该方法返回与字段相同的东西,但是由于它是一种方法,因此调用者可以使用它来生成任何类型的通用类型的列表(而该字段不能像这样灵活)。

There is an unchecked cast in there (with a warning), but since the list is empty, we (unlike the compiler) know it is safe. 那里有一个未经检查的强制转换(带有警告),但是由于列表为空,我们(与编译器不同)知道它是安全的。

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

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