When to use a List over an Array in Java?

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

提交回复
热议问题