简体   繁体   English

在Java Arraylist上添加/删除

[英]Add/Remove on Java Arraylist

I happen not to give any thoughts about this but I have been doing this for quite a while in a project that I am working on. 我碰巧没有对此进行任何思考,但是在我正在从事的项目中我已经做了很长时间了。

public class Test {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new DumbBean("A"));
        list.add(new DumbBean("B"));
        list.add(new DumbBean("C"));
        System.out.println(list);

        list.add(1, new DumbBean("D"));

        System.out.println(list);

        list.remove(2);
        System.out.println(list);
    }
}

It actually works in my case. 在我看来,它实际上是有效的。 I do a lot of insert/delete/add on a java arraylist. 我在java arraylist上做了很多插入/删除/添加操作。

I happen to think if I am overlooking something or is there a better alternative to this. 我碰巧想到如果我忽略了某件事,还是有更好的替代方法。 (...another collection?) (...另一个集合?)

Thanks 谢谢

If you find yourself appending to the end of the list a lot, I'd go with the ArrayList. 如果您发现自己经常添加到列表的末尾,我将使用ArrayList。 If you find yourself inserting and removing in the middle, I'd go with a LinkedList. 如果您发现自己在中间插入和删除,则可以使用LinkedList。

If you deal with lists that are less than length 20, I'd forget about this entirely. 如果您处理的列表长度小于20,那么我会完全忘记这一点。 Unless you have performance metrics that indicate this is a bottleneck for your program, this isn't even worth your time. 除非您有性能指标表明这是程序的瓶颈,否则这根本不值得您花时间。

Here is a good comparison of data structures: 这是数据结构的良好比较:

http://en.wikipedia.org/wiki/Comparison_of_data_structures http://en.wikipedia.org/wiki/Comparison_of_data_structures

It's good that you already know that you will have a lot of inserts and deletes as this will help you decide on which is better. 很好,您已经知道您将有很多插入和删除操作,因为这可以帮助您确定哪种更好。 Remember, some structures you will need to search before deleting or inserting in place. 请记住,在删除或插入到位之前,您需要搜索一些结构。

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

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