Type List vs type ArrayList in Java
In Java, List
is an interface that defines a list data structure, while ArrayList is a class that implements the List
interface.
The List
interface is part of the java.util
package and is defined as follows:
public interface List<E> extends Collection<E> {
// ...
}
It extends the Collection
interface and provides methods for manipulating a list, such as adding, removing, and accessing elements.
The ArrayList class is also part of the java.util
package and is defined as follows:
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable {
// ...
}
It extends the AbstractList
class and implements the List
, RandomAccess
, Cloneable
, and Serializable
interfaces. It provides a resizable array implementation of the List
interface and allows you to access and manipulate elements using an index.
To use an ArrayList, you can create an instance of the class and add elements to it:
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
In this example, the list
variable is a reference to an ArrayList object that stores strings. The add()
method is used to add elements to the list.
You can also use the List
interface as a type and use an ArrayList or any other class that implements the List
interface as the implementation:
List<String> list = new ArrayList<>();
In this example, the list
variable is a reference to a List
interface, but the actual implementation is an ArrayList.
I hope this helps. Let me know if you have any questions.