This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/2…
Issue an overview
I now have to use Java to keep thousands of strings in memory for sequential access.
Should I store them in an array or should I use some kind of List?
Since arrays store all data in contiguous chunks of memory (as opposed to lists), is it a problem to use arrays to store thousands of strings?
Best answer
I recommend using profiler to test which is faster. I personally think you should use List.
I work on a large code base, and a previous group of developers used arrays everywhere. It makes the code very inflexible. After changing most of its code to List, we noticed that there was no difference in speed.
Other answer
The Java way is that you should consider the data abstraction that best suits you. Remember that in Java, lists are abstractions, not concrete data types. You should declare the string as a List and then initialize it using the ArrayList implementation.
List<String> strings = new ArrayList<String>();
Copy the code
This separation of abstract data types from specific implementations is one of the key aspects of object-oriented programming.
ArrayList implements List Abstract Data Type using an array as its base implementation. The access speed is virtually the same as an array, with the added advantage of being able to add and subtract elements from a List (although this is an O (n) operation using ArrayList), and if you decide to change the underlying implementation later, you can. For example, if you realize you need synchronous access, you can change the implementation to Vector without rewriting all the code.