When to use a List over an Array in Java?

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

    I see the question as being the opposite-

    When should you use an Array over a List?

    Only you have a specific reason to do so (eg: Project Constraints, Memory Concerns (not really a good reason), etc.)

    Lists are much easier to use (imo), and have much more functionality.

    Note: You should also consider whether or not something like a Set, or another datastructure is a better fit than a List for what you are trying to do.

    Each datastructure, and implmentation, has different pros/cons. Pick the ones that excel at the things that you need to do.

    If you need get() to be O(1) for any item? Likely use an ArrayList, Need O(1) insert()? Possibly a Linked List. Need O(1) contains()? Possibly a Hashset.

    TLDR: Each data structure is good at some things, and bad at others. Look at your objectives and choose the data structure that best fits the given problem.

    Edit:

    One thing not noted is that you're better off declaring the variable as its interface (i.e. List or Queue) rather than its implementing class. This way, you can change the implementation at some later date without changing anything else in the code.

    As an example:

    List myList = new ArrayList(); 
    

    vs

    List myList = new LinkedList(); 
    

    Note that myList is a List in both examples. --R. Bemrose

提交回复
热议问题