【问题标题】:Insert object into List wildcard extending interface将对象插入列表通配符扩展接口
【发布时间】:2015-04-23 08:48:05
【问题描述】:

所以我有一个界面

public interface Identity {

abstract void setKey(String key);
abstract String getKey();
}

我想用于插入排序功能

public static void InsertIdentity(Identity identity, ArrayList<? extends Identity> list) {
    int i = 0;
    Identity id;
    while (i < list.size()) {
        if ((id = list.get(i)).getKey().compareTo(identity.getKey()) < 0) {
            i++;
        }else{break;}
    }
    list.add(i, identity);
}

但显然我不能将身份添加到 ArrayList - ?扩展身份

我想知道是否有办法解决这个问题?

我知道 Java 有其他方法来完成这项任务,但我希望这个功能能够工作。

【问题讨论】:

  • Java generic collection, cannot add list to list 的可能重复项。还有更多关于这个问题的问题......
  • 我知道为什么它不起作用,我希望有人能帮我找到解决办法
  • 解决方法是不要使用上限通配符声明您的参数。
  • 但是它违背了函数的目的
  • 您显然想让您的方法适用于各种类型。这需要一个类型参数:&lt;T extends Identity&gt; void insertIdentity(T identitiy, List&lt;T&gt; list) { ... }。顺便说一句:继续使用 Java 的代码约定,并在适当的地方使用接口。

标签: java interface insert wildcard extends


【解决方案1】:

你可以制作method generic:

public static <T extends Identity> void InsertIdentity(T identity, ArrayList<T> list) {
    //...

如果您使用这种方法,您可能还需要将其他方法设为通用。

【讨论】:

  • 非常感谢!我早些时候试图做这样的事情,但无法让它发挥作用。现在我知道了!
【解决方案2】:

我建议如下:

public static <I extends Identity> void InsertIdentity(I identity, ArrayList<I> list) 

【讨论】:

  • 非常感谢!我早些时候试图做这样的事情,但无法让它发挥作用。现在我知道了!
【解决方案3】:

这是否可行,具体取决于您将如何使用 InsertIdentity 方法:

public static <T extends Identity> void InsertIdentity(T identity, ArrayList<T> list) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多