In Java, you can use the java.util.List
interface to declare a list that can hold elements of a specific type. The List
interface is a part of the Java Collections Framework and provides a way to store a sequence of elements in an ordered collection.
To declare a list in Java, you need to specify the element type between angle brackets (<
and >
) after the List
interface. For example:
List<String> myList;
This declaration creates a new variable myList
that refers to a list of strings.
To create a new list object, you can use one of the concrete implementations of the List
interface, such as ArrayList
, LinkedList
, or Vector
. Here is an example of how to create a new ArrayList
object and assign it to the myList
variable:
myList = new ArrayList<String>();
This creates a new ArrayList
object that can hold strings and assigns it to the myList
variable. You can then use the methods provided by the List
interface, such as add
, remove
, and get
, to manipulate the elements in the list.
For example:
myList.add("Hello"); // Add an element to the list myList.add("World"); System.out.println(myList.get(0)); // Get the first element in the list myList.remove(1); // Remove the second element from the list
This code adds two elements to the list, retrieves the first element, and removes the second element.
You can use the List
interface and its concrete implementations to create lists of any type, as long as the element type is specified between the angle brackets. For example, you can create a list of integers, a list of objects, or a list of lists.