简体   繁体   English

不带有通配符的Java泛型

[英]Java Generics with Wildcards Not Compiling

I'm having trouble understanding the finer points of Java generics with wildcards. 我很难理解通配符对Java泛型的优点。 specifically, why doesn't this compile. 具体来说,为什么不编译。

public class Test {

    abstract class Function<A, B> {
        abstract B call(A a);
    }

    interface PropertyType {
        String bubbles();
    }

    class Apartment implements PropertyType {
        @Override
        public String bubbles() {
            return "bubbles";
        }
    }

    public void invokeFunctionOnAList() {
        List<Apartment> apts = new ArrayList<Apartment>();
        functionLoop(apts, new Function<Apartment, String>() {

            @Override
            String call(Apartment a) {
                return a.bubbles();
            }
        });
    }

    public void functionLoop(List<? extends PropertyType> list, Function<? extends PropertyType, String> t) {
        for (PropertyType p : list) {
            t.call(p);
        }
    }
}

The most formally correct way to put that code actually is 实际放置该代码的最形式正确的方法是

public <C extends PropertyType> void functionLoop(
        List<C> list, Function<? super C, String> t) {
    for (C p : list) {
        t.call(p);
    }
}

The best explanation of generics I found was on "Effective Java" by Joshua Bloch. 我发现的泛型的最佳解释是Joshua Bloch撰写的“ Effective Java”。 You can find a small excerpt which can relate to your example in this presentation . 您可以在本演示文稿中找到与您的示例相关的小摘录。

Your compiler does not know if you are using same type in List and Function. 您的编译器不知道您是否在List和Function中使用相同的类型。 Therefore you have to tell him this. 因此,您必须告诉他这一点。

Try this: 尝试这个:

public <C extends PropertyType>void functionLoop(
                         List<C> list, Function<C, String> t) {
  for (C p : list) {
    t.call(p);
  }
}

because call(Apartment a) should get Apartment object as a parameter and you pass a PropertyType object. 因为call(Apartment a)应该将Apartment对象作为参数,并且您传递了PropertyType对象。 THough Apartment is-a PropertyType , but PropertyType is-NOT-a Appartment . 虽然Apartment是-一个PropertyType ,但PropertyType是-NOT-一个Appartment

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

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