Curriculum
In Java, a List
is an ordered collection of elements, with duplicates allowed. The List
interface is a part of the java.util
package, and it is implemented by several classes, including ArrayList
, LinkedList
, and Vector
. Here’s an example of how to create a List
and add elements to it using an ArrayList
:
import java.util.ArrayList; import java.util.List; public class ListExample { public static void main(String[] args) { List<String> myList = new ArrayList<>(); myList.add("apple"); myList.add("banana"); myList.add("cherry"); System.out.println(myList); } }
In this example, we create an ArrayList
called myList
, and then we add three elements to it using the add()
method. Finally, we print out the contents of the list using the toString()
method.
Here are some common methods provided by the List
interface:
add(E element)
: adds an element to the end of the listadd(int index, E element)
: adds an element at the specified indexget(int index)
: returns the element at the specified indexremove(int index)
: removes the element at the specified indexset(int index, E element)
: replaces the element at the specified index with the specified elementsize()
: returns the number of elements in the listcontains(Object o)
: returns true
if the list contains the specified element, and false
otherwiseindexOf(Object o)
: returns the index of the first occurrence of the specified element in the list, or -1 if the element is not presentlastIndexOf(Object o)
: returns the index of the last occurrence of the specified element in the list, or -1 if the element is not presentIn addition to these methods, the List
interface provides several other methods for working with lists, including methods for sorting, sublists, and iterators.
One important thing to note about List
is that it is an ordered collection, which means that the elements are stored in a specific order and can be accessed by their index. This makes List
a good choice for use cases where the order of the elements is important and needs to be preserved. However, it also means that operations like inserting or removing elements from the middle of the list can be slow, since all the subsequent elements may need to be shifted to make room. In cases where you need to frequently add or remove elements in the middle of a collection, a LinkedList
may be a better choice, since it provides faster insertion and removal operations.