When to use a List over an Array in Java?

前端 未结 9 804
盖世英雄少女心
盖世英雄少女心 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:21

    In many cases the type of collection used is an implementation detail which shouldn't be exposed to the outside world. The more generic your returntype is the more flexibility you have changing the implementation afterwards.

    Arrays (primitive type, ie. new int[10]) are not generic, you won't be able to change you implementation without an internal conversion or altering the client code. You might want to consider Iterable as a returntype.

    0 讨论(0)
  • 2020-11-27 06:22

    If you know how many things you'll be holding, you'll want an array. My screen is 1024x768, and a buffer of pixels for that isn't going to change in size ever during runtime.

    If you know you'll need to access specific indexes (go get item #763!), use an array or array-backed list.

    If you need to add or remove items from the group regularly, use a linked list.

    In general, dealing with hardware, arrays, dealing with users, lists.

    0 讨论(0)
  • 2020-11-27 06:23

    Pretty much always prefer a list. Lists have much more functionality, particularly iterator support. You can convert a list to an array at any time with the toArray() method.

    0 讨论(0)
  • 2020-11-27 06:24

    It depends on what kind of List.

    It's better to use a LinkedList if you know you'll be inserting many elements in positions other than the end. LinkedList is not suitable for random access (getting the i'th element).

    It's better to use an ArrayList if you don't know, in advance, how many elements there are going to be. The ArrayList correctly amortizes the cost of growing the backing array as you add more elements to it, and is suitable for random access once the elements are in place. An ArrayList can be efficiently sorted.

    0 讨论(0)
  • 2020-11-27 06:26

    Rules of thumb:

    • Use a List for reference types.
    • Use arrays for primitives.
    • If you have to deal with an API that is using arrays, it might be useful to use arrays. OTOH, it may be useful to enforce defensive copying with the type system by using Lists.
    • If you are doing a lot of List type operations on the sequence and it is not in a performance/memory critical section, then use List.
    • Low-level optimisations may use arrays. Expect nastiness with low-level optimisations.
    0 讨论(0)
  • 2020-11-27 06:28

    If you want the array of items to expand (i.e. if you don't know what the size of the list will be beforehand), a List will be beneficial. However, if you want performance, you would generally use an array.

    0 讨论(0)
提交回复
热议问题