Explain Codes LogoExplain Codes Logo

"instantiating" a List in Java?

java
interface-vs-class
list-implementation
polymorphism
Nikita BarsukovbyNikita Barsukov·Jan 25, 2025
TLDR

In Java, choose ArrayList or LinkedList to instantiate a List. Here's a code snippet for initializing an ArrayList:

List<String> list = new ArrayList<>();

In the example above, we've habituated a List of Strings. Java's diamond operator lets you keep it short and neat.

Interface vs Class

In Java's type system, "List" is an interface, not a concrete class. Attempting to instantiate an interface is a no-go, as an interface is akin to a contract that classes sign agreeing to provide certain methods.

Implementations: ArrayList vs LinkedList

Two popular implementations of the List interface are ArrayList and LinkedList. Choose according to your needs - ArrayList shines in lookup scenarios; LinkedList excels during insertions and deletions.

Custom Implementation: Not Always Required

Creating a custom implementation of the List interface can be thrilling, but it's not always the game-changer. The off-the-shelf ones like ArrayList and LinkedList are adept at handling most use cases.

LinkedList: The Insert/Delete Maven

When your application involves frequent insertions and deletions, particularly in the middle of the List, LinkedList works like a charm.

ArrayList: The Random Access Maestro

When you need fast access to elements by their indices, Duke's choice is ArrayList - it can fetch any element in constant time.

When you try the impossible

Are you trying to instantiate a List interface directly and getting the error "java.util.List is abstract; cannot be instantiated"? Remind yourself in Java, Interfaces are for inspiration, classes are for implementation.

Glad you asked about Upcasting

Creating an ArrayList instance and assigning it to a List reference is a brilliant way of keeping your options open. Flexibility thy name is upcasting!

Polymorphism in Play

With upcasting, you can switch between ArrayList and LinkedList without breaking a sweat - that's the charm of polymorphism. High five to the principle of coding to an interface, not an implementation!💡

Java vs. .NET: Lists Explored

In the .NET world, you can instantiate a list directly. But Java prefers you to make an informed decision, choosing either ArrayList or LinkedList, depending on your use case.

When standard isn't enough

Sometimes you might need to add a little extra spice - extending ArrayList or LinkedList can allow you to customize your List's behavior.