When to use a List over an Array in Java?

前端 未结 9 921
盖世英雄少女心
盖世英雄少女心 2020-11-27 06:08

In Java, when would it be preferential to use a List rather than an Array?

9条回答
  •  不知归路
    2020-11-27 06:38

    Most people have answered it already.

    There are almost no good reason to use an array instead of List. The main exception being the primitive array (like int[]). You cannot create a primitive list (must have List).

    The most important difference is that when using List you can decide what implementation will be used. The most obvious is to chose LinkedList or ArrayList.

    I would like to point out in this answer that choosing the implementation gives you very fine grained control over the data that is simply not available to array:

    1. You can prevent client from modifying your list by wrapping your list in a Collection.unmodifiableList
    2. You can synchronize a list for multithreading using Collection.synchronizedList
    3. You can create a fixed length queue with implementation of LinkedBlockingQueue
    4. ... etc

    In any case, even if you don't want (now) any extra feature of the list. Just use an ArrayList and size it with the size of the array you would have created. It will use an Array in the back-end and the performance difference with a real array will be negligible. (except for primitive arrays)

提交回复
热议问题