繁体   English   中英

如何从列表界面实现添加方法

[英]How to implement add method from List interface

我想为自己的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。

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

当您在原始添加迭代器方法的列表中覆盖List方法时,所有这些方法都已销毁,因此我认为最好不要覆盖这些方法。 如果您有兴趣查看列表源代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM