🆚 List list = new ArrayList();
vs ArrayList list = new ArrayList();
Feature | List list = new ArrayList(); | ArrayList list = new ArrayList(); |
---|---|---|
Reference Type | Interface (List ) | Concrete class (ArrayList ) |
Flexibility | ✅ High – you can easily switch to LinkedList , etc. | ❌ Low – tightly bound to ArrayList |
Recommended? | ✅ Yes – follows programming to interface | ⚠️ Only when ArrayList-specific methods are needed |
Usage Style | Polymorphic | Direct instantiation and reference |
Best Practice | Good for API design, abstraction, and reusability | Good for internal/private use when type won’t change |
💡 Real-World Example
// Flexible, preferred for most cases
List<String> names = new ArrayList<>();
// Later, you can change it to:
names = new LinkedList<>();
// Fixed to one class
ArrayList<String> names = new ArrayList<>();
// Cannot be changed to LinkedList without changing the reference type
🧠 Interview Tip
“Why should we prefer List
on the left-hand side?”
Because it supports polymorphism. Your code depends on behavior, not a specific implementation. This makes it easier to update, test, or replace one list type with another without rewriting dependent code.