gpt4 book ai didi

java - 将对象插入List通配符扩展接口(interface)

转载 作者:行者123 更新时间:2023-12-01 06:50:55 25 4
gpt4 key购买 nike

所以我有一个界面

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);
}

但显然我无法将 Identity 添加到 ArrayList - ?扩展身份

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

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

最佳答案

你可以制作 method generic :

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

如果您使用此方法,您可能还需要使其他方法通用。

关于java - 将对象插入List通配符扩展接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29818234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com