gpt4 book ai didi

java - 扩展 ArrayList 和创建新方法

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:15 25 4
gpt4 key购买 nike

我在掌握某些东西时遇到了一些问题 - 我可能会完全错误地处理这件事。

我正在尝试创建一个扩展 ArrayList 的类,但有几个方法可以增加功能(至少对于我正在开发的程序而言。)

其中一个方法是 findById(int id),它在每个 ArrayList 对象中搜索特定的 id 匹配项。到目前为止它的工作,但它不会让我做 for (Item i : this) { i.getId(); }

我不明白为什么?

完整代码:

public class CustomArrayList<Item> extends ArrayList<Item> {

// declare singleton instance
protected static CustomArrayList instance;

// private constructor
private CustomArrayList(){
// do nothing
}

// get instance of class - singleton
public static CustomArrayList getInstance(){
if (instance == null){
instance = new CustomArrayList();
}
return instance;
}

public Item findById(int id){
Item item = null;
for (Item i : this) {
if (i.getId() == id) {
// something
}
}
return item;
}
public void printList(){
String print = "";
for (Item i : this) {
print += i.toString() + "\n";
}
System.out.println(print);
}
}

最佳答案

改变

public class CustomArrayList<Item> extends ArrayList<Item> {

public class CustomArrayList extends ArrayList<Item> {

我怀疑Item是要存储在列表中的类的名称。通过添加 <Item>CustomArrayList 之后您正在引入一个类型参数,它会影响此类。


<Item>参数,你的代码等于

public class CustomArrayList<T> extends ArrayList<T> {
// ...
for (T i : this) { i.getId(); }
// ...
}

这显然不会总是有效,因为 T可以指任何类型。

关于java - 扩展 ArrayList 和创建新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6524711/

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