Quick Reach
The list in Java
The List is an interface of the Collection or you can say it extends the Collection. A List is an ordered collection of the elements with integer-based index.
A few main points about List Java interface are:
- Elements can be added, removed and searched in the Java list, whereas you can add elements at the specified positions.
- The index for list elements, just like arrays, starts from 0 (which is an integer).
- The list may contain duplicate elements.
A List example
How to use list interface?
In order to use the List interface in your projects you must import the Java List as follows:
Import java.util.*;
How to make a list
After importing the java.util.* package, it is time to declare an object to create a new List.
List list_name = new ArrayList();
Or
List list_name = new LinkedList();
As such, the List is an interface, you cannot initialize a List object. The List is implemented in various classes like ArrayList, LinkedList, Vector, and Stack.
Example of creating and printing List elements
The following example shows how to create a new List object. It adds five elements and then a for loop is used to display the List elements.
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<b>import</b> java.util.*;
public class list_example {
public static void main(String []args) {
List Intlist = new ArrayList (5); //Declaring List
Intlist.add(10);
Intlist.add(20);
Intlist.add(30);
Intlist.add(40);
Intlist.add(50);
//Displaying List
for (int i=0;i<Intlist.size();i++){
System.out.println(Intlist.get(i));
}
}
}
|
The output will be:
10
20
30
40
50
You can also use methods of the List interface to add, remove, search the elements in a List.
A few common methods of Java List are:
- public void add(int index,Object element);
- public object remove(int index);
- public object get(int Index position);
- public object set(int index,Object element);
Read Further: Java collection | Java ArrayList | Java Vector
Leave A Comment?