The declaration of
List
Interface is :
interface List< E
>
Here,
E
specifies type of objects that list contains.
The methods defined by
List
:
These methods are illustrated in the following example:
ListMethods
import java.util.*;
class ListMethods
{
public static void main(String arg[])
{
List<Integer> marks = new ArrayList<Integer>();
marks.add(200);
marks.add(210);
marks.add(226);
for (Integer x : marks) {
System.out.print(x + " ");
}
System.out.println();
marks.add(1, 30); // void add(int index, E obj)
for (Integer x : marks) {
System.out.print(x + " ");
}
System.out.println();
System.out.println(marks.get(2));
System.out.println(marks.indexOf(1));
System.out.println(marks.remove(2)); // Removes element at index 2.
for (Integer x : marks) // Resulting list after removing element.
{
System.out.print(x + " ");
}
System.out.println();
System.out.println(marks.set(0, 5)); // Sets element at index 0.
for (Integer x : marks) // Resulting list after setting the element at index 0.
{
System.out.print(x + " ");
}
}
}
OUTPUT200 210 226
200 30 210 226
210
-1
210
200 30 226
200
5 30 226
DESCRIPTIONThe first line is just the display of elements in the listmarks
. The second line is the display of elements in the list marks
after adding the element 30
at index 1
. The third line the display of element at index 2
using get()
. The fourth line is the display of the index of the element 1
that is 0. The fifth line is the display of the element to be removed at the index 2
. The sixth line is the display of the elements after removing the element 10
from the list marks
. The seventh line is the display of the element at index 0
which is being set with the new element, the old element is returned that is 1.The last line is the display of the elements of the list after setting the zeroth element with 5.