我想为我的Customlist实现add方法,该方法在java中实现List。代码如下所示:
public class CustomList implements List{
private List list;
public boolean add(Object s) {
boolean check = false;
try {
System.out.println("LOG: now performing the addition of an object");
long startTime = System.nanoTime();
check = list.add(s);
long estimatedTime = System.nanoTime() - startTime;
System.out.println(estimatedTime);
System.out.println();
}
catch (Exception e) {
e.printStackTrace();
}
return check;
}
public CustomList(List l) {
list = l;
}
}
然而,当我在我的主要方法中使用它时,它不起作用。似乎只有我在Customlist中的列表实际上添加了新的Object,但在main方法中,它没有。我怎么能解决这个问题,谢谢。 这是TestCases类中的主要方法:
public class TestCases {
private static CustomList t = new CustomList(new ArrayList());
public static void main(String[] args) throws IOException {
t.add("abcd");
for(Object temp : t) {
System.out.println(temp);
}
}
}
更新:我只为每个循环包含了一个用于测试的循环,但是它不会打印任何内容而且我得到了Null Pointer Exception。
答案 0 :(得分:0)
import java.util.ArrayList;
import java.util.List;
public class CustomList<E> extends ArrayList<E>{
List list;
public CustomList(List l) {
list = l;
}
}
测试代码
public class TestCases {
private static CustomList t = new CustomList(new ArrayList());
public static void main(String[] args) throws IOException {
t.add("abcd");
System.out.println(t.size());
for(Object temp : t) {
System.out.println(temp);
}
}
}
操作结果:
1
abcd
当你覆盖原始add迭代器方法列表中的List方法全部被破坏时,我认为最好不要覆盖这些方法。 如果您有兴趣查看List源代码