-4

On which basis should we choose to use List, LinkedList, ArrayList in Java?.

Also please explain which one is better to use?.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Worth mentioning that `List` is an interface, whereas `ArrayList` (and `LinkedList`) are _an implementation_ of a `List`. – Martin Marconcini Nov 05 '21 at 15:04
  • 1
    Welcome to StackOverflow! Please refer to the guide on [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and when needed, how to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) so people can try to help you with a problem. You're often expected to do your own homework and research before asking a question. – Martin Marconcini Nov 05 '21 at 15:20
  • Note that Java's implementation of linked list is limited. There is no equivalent to C++ std::list::splice(), which is used to move nodes within or between lists. Java's linked list iterators can't be shallow copied, assignment just creates another pointer to the same iterator object. If something is inserted or removed from a linked list, than all iterators to that list are invalidated (or all but the iterator used to do the insert or delete). It's better to create your own linked list class due to these issues. – rcgldr Nov 05 '21 at 19:40

1 Answers1

1

List is an interface, it should be the type of your variables or the arguments of your methods.

The other two are implementations of this interface.

LinkedList is optimized for inserts and deletes.

ArrayList is optimized for random access.

So, you can choose based on the kind of work you are going to do.

Andres
  • 10,561
  • 4
  • 45
  • 63
  • 2
    In theory `LinkedList` is optimized for insert and deletes, but in practice using an `ArrayList` is almost always going to perform better. – Mark Rotteveel Nov 05 '21 at 15:15