When to use a List over an Array in Java?

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

提交回复
热议问题