Learn about Java List
Introduction
We will study the Java List interface and its methods in this tutorial. The List interface in Java is a sequentially accessed ordered collection that lets us store elements. The Collection interface is expanded by it..
Classes that Implement List
- List is an interface, so we are unable to make objects from it. These classes can be used to access features of the List interface:
- ArrayList
- LinkedList
- Vector
- Stack
The List interface is implemented by these classes, which are described in the Collections framework.
How to use List?
Use of List in Java requires the import of the java.util.List package.
// ArrayList implementation of List |
Here, we've made objects of the classes ArrayList and LinkedList called list1 and list2, respectively. These objects can make use of the List interface's features.
Methods of List
All of the Collection interface's methods are available on the List interface. It's because Collection is a superset of List's interface. The following are some frequently used Collection interface methods that are also offered in the List interface:
- add() - expands a list by one element
- addAll() - adds all of a list's components to another.
- get() - aids in accessing random elements from lists
- iterator() - produces an iterator object that may be used to access items of lists consecutively.
- set() - alters list items
- remove() - removes a list item from it
- removeAll() - removes all of the list's elements
- clear() - removes all of the list's elements (more quickly than removeAll()).
- size() - lists' length is returned
- toArray() - list to array conversion
- contains() - returns true if the supplied element is present in the list.
Implementation of the List Interface
Implementing the ArrayList Class
import java.util.List; |
Implementing the LinkedList Class
import java.util.List; |
Java List vs. Set
The Collection interface is inherited by both the List interface and the Set interface. There are some differences between them, though. Duplicate items are permitted in lists. Sets, however, are unable to include duplicate items. List elements are kept in a certain sequence. However, much like in mathematics, set elements are kept in groups.