我想在Java中为ArrayList创建自己的toString()方法.但是,即使我将这样的toString()添加到包含ArrayList的类中,我也无法使其工作.
@Override
public String toString() {
String result = "+";
for (int i = 0; i < list.size(); i++) {
result += " " + list.get(i);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
当我像这样调用我的ArrayList时list.toString(),我仍然得到默认表示.我错过了什么吗?
我抓住了一些问题 - 我可能会对此完全错误.
我正在尝试创建一个扩展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) …Run Code Online (Sandbox Code Playgroud)