扩展 ArrayList 并创建新方法 [英] Extending ArrayList and Creating new methods
问题描述
我在抓住某些东西时遇到了一些问题 - 我可能完全错误.
I'm having a bit of a problem grasping something - I might be going about this completely wrong.
我正在尝试创建一个扩展 ArrayList 的类,但有几个方法可以增加功能(至少对于我正在开发的程序而言).
I am trying to create a class which extends ArrayList but has several methods which increase the functionality (at least for the program I am developing.)
其中一种方法是 findById(int id),它搜索每个 ArrayList 对象以查找特定的 id 匹配项.到目前为止它正在工作,但它不会让我做 for (Item i : this) { i.getId();}
One of the methods is a findById(int id), which searches each ArrayList object for a particular id match. So far it's working, but it won't let me do 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
是您要存储在列表中的类的名称.通过在 CustomArrayList
之后添加
,您引入了一个 类型参数,它隐藏了这个类.
I suspect Item
is the name of the class that you want to store in the list. By adding <Item>
after CustomArrayList
you're introducing a type parameter which shadows this class.
使用
参数,你的代码等于
public class CustomArrayList<T> extends ArrayList<T> {
// ...
for (T i : this) { i.getId(); }
// ...
}
这显然不会总是有效,因为 T
可能指任何类型.
which obviously won't always work, as T
may refer to any type.
这篇关于扩展 ArrayList 并创建新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!