Array or List in Java. Which is faster?

后端 未结 30 1622
滥情空心
滥情空心 2020-11-22 04:30

I have to keep thousands of strings in memory to be accessed serially in Java. Should I store them in an array or should I use some kind of List ?

Since arrays keep

30条回答
  •  不思量自难忘°
    2020-11-22 05:14

    Well firstly it's worth clarifying do you mean "list" in the classical comp sci data structures sense (ie a linked list) or do you mean java.util.List? If you mean a java.util.List, it's an interface. If you want to use an array just use the ArrayList implementation and you'll get array-like behaviour and semantics. Problem solved.

    If you mean an array vs a linked list, it's a slightly different argument for which we go back to Big O (here is a plain English explanation if this is an unfamiliar term.

    Array;

    • Random Access: O(1);
    • Insert: O(n);
    • Delete: O(n).

    Linked List:

    • Random Access: O(n);
    • Insert: O(1);
    • Delete: O(1).

    So you choose whichever one best suits how you resize your array. If you resize, insert and delete a lot then maybe a linked list is a better choice. Same goes for if random access is rare. You mention serial access. If you're mainly doing serial access with very little modification then it probably doesn't matter which you choose.

    Linked lists have a slightly higher overhead since, like you say, you're dealing with potentially non-contiguous blocks of memory and (effectively) pointers to the next element. That's probably not an important factor unless you're dealing with millions of entries however.

提交回复
热议问题