【问题标题】:generic interface: list of something specific通用接口:特定事物的列表
【发布时间】:2009-05-04 16:56:35
【问题描述】:

我想定义一个接口 MyList,它是一个接口 MyThing 的列表。 MyList 的部分语义是它的操作对没有实现 MyThing 接口的对象没有任何意义。

这是正确的声明吗?

interface MyList<E extends MyThing> extends List<E> { ... }

编辑:(第 2 部分)现在我有了另一个接口,它返回 MyList 作为其方法之一。

// I'm defining this interface
// it looks like it needs a wildcard or template parameter
interface MyPlace {
    MyList getThings();
}

// A sample implementation of this interface
class SpecificPlace<E extends MyThing> implements MyPlace {
    MyList<E> getThings();
}

// maybe someone else wants to do the following
// it's a class that is specific to a MyNeatThing which is
// a subclass of MyThing
class SuperNeatoPlace<E extends MyNeatThing> implements MyPlace {
    MyList<E> getThings();
    // problem?
    // this E makes the getThings() signature different, doesn't it?
}

【问题讨论】:

    标签: java generics interface


    【解决方案1】:

    是的,至少EnumSet 是这样做的。

    public abstract class EnumSet<E extends Enum<E>>
    extends AbstractSet<E>


    修改第 2 部分的答案:

    我不确定为什么接口中getThings() 的返回类型不会抱怨原始类型。我怀疑由于类型擦除,接口中的警告即使存在也是无用的(如果将返回类型更改为List,也没有警告)。

    对于第二个问题,由于MyNeatThing 扩展了MyThingE 在其范围内。这就是在泛型参数中使用extends 绑定的意义所在,不是吗?

    【讨论】:

    • 嘿,等一下,Lists 作为消费者而我们应该使用 super 时发生了什么?
    • 你不能在类类型参数声明中使用super,这样我就不用去想答案了。 ;)
    • 我认为您混淆了 2 个问题,尽管我不确定。我认为您从未见过 SomeClass。你有时会看到 SomeClass super Something> 当该类型用于指定方法参数时。 ibm.com/developerworks/java/library/j-jtp07018.html
    • 一些JLS链接:类型参数(java.sun.com/docs/books/jls/third_edition/html/…)不能使用super。但是参数化类型(java.sun.com/docs/books/jls/third_edition/html/…)可以。所以这与另一个问题完全不同。
    • re:“我不确定为什么返回类型 ... 没有抱怨”——我的评论“它看起来需要参数或通配符”是我想知道的,而不是编译器抱怨。我想我仍然在掌握泛型的微妙之处......
    【解决方案2】:

    对于第 1 部分,是的,看起来不错。

    对于您的第 2 部分,我建议如下内容。该方法返回一个 MyList 的东西,你不知道它是什么(显然不同的实现是不同的),但你知道它是 MyThing 的子类型。

    interface MyPlace {
        MyList<? extends MyThing> getThings();
    }
    

    【讨论】:

      【解决方案3】:

      请记住,正确实现 java.util.List 之类的接口很难;所以问问自己所有这些问题:

      • 我可以“按原样”使用 java.util.List 吗? 我需要添加/删除功能吗?
      • 有没有更简单的我可以实现的东西,比如 Iterable
      • 我可以使用合成吗? (相对于继承)
      • 我能找到 新需要的功能 现有的库,如 Google 收藏?
      • 如果我需要 添加/删除功能,值得吗 增加的复杂性?

      也就是说,您可能只使用 java.util.List 作为示例:

      interface MyPlace<T extends MyThing> {
         List<T> getThings();
      }
      
      class SpecificPlace implements MyPlace<MyThing> {
         public List<MyThing> getThings() { return null; }
      }
      
      class SuperNeatoPlace implements MyPlace<MyNeatThing> {
         public List<MyNeatThing> getThings() { return null; }
      }
      

      【讨论】:

      • 哦,当然:我将把其中大部分委托给内部私人名单。
      • 问题不在于它的列表方面(将 List 替换为 Foo,我的问题保持不变),而在于泛型方面。
      猜你喜欢
      • 2018-12-24
      • 2011-01-22
      • 1970-01-01
      • 2014-04-06
      • 2016-03-13
      • 2019-01-27
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多