List Interface in Java with Examples

The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayListLinkedListVector and Stack classes.

List Interface in Java with Examples

Creating List Objects: 
List is an interface, and the instances of List can be created in the following ways:

List a = new ArrayList();
List b = new LinkedList();
List c = new Vector(); 
List d = new Stack(); 

Generic List Object:
After the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List. The type-safe List can be defined in the following way:

// Obj is the type of object to be stored in List.
List<Obj> list = new List<Obj> ();   

Operations on List:
List Interface extends Collection, hence it supports all the operations of Collection Interface, along with following additional operations:

1 Positional Access:  访问的方法
List allows add, remove, get and set operations based on numerical positions of elements in List. List provides following methods for these operations:

  • void add(int index,Object O): This method adds given element at specified index.
  • boolean addAll(int index, Collection c): This method adds all elements from specified collection to list. First element gets inserted at given index. If there is already an element at that position, that element and other subsequent elements(if any) are shifted to the right by increasing their index.
  • Object remove(int index): This method removes an element from the specified index. It shifts subsequent elements(if any) to left and decreases their indexes by 1.
  • Object get(int index): This method returns element at the specified index.
  • Object set(int index, Object new): This method replaces element at given index with new element. This function returns the element which was just replaced by new element.
// Java program to demonstrate positional access 
// operations on List interface 
import java.util.*; 

public class ListDemo 
{ 
	public static void main (String[] args) 
	{ 
		// Creating a list 
		List<Integer> l1 = new ArrayList<Integer>(); 
		l1.add(0, 1); // adds 1 at 0 index 
		l1.add(1, 2); // adds 2 at 1 index 
		System.out.println(l1); // [1, 2] 

		// Creating another list 
		List<Integer> l2 = new ArrayList<Integer>(); 
		l2.add(1); 
		l2.add(2); 
		l2.add(3); 

		// Will add list l2 from 1 index 
		l1.addAll(1, l2); 
		System.out.println(l1); 

		// Removes element from index 1 
		l1.remove(1);	 
		System.out.println(l1); // [1, 2, 3, 2] 

		// Prints element at index 3 
		System.out.println(l1.get(3)); 

		// Replace 0th element with 5 
		l1.set(0, 5); 
		System.out.println(l1); 
	} 
} 

Output:

[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]

2 Search:
List provides methods to search element and returns its numeric position. Following two methods are supported by List for this operation:

  • int indexOf(Object o): This method returns first occurrence of given element or -1 if element is not present in list.
  • int lastIndexOf(Object o): This method returns the last occurrence of given element or -1 if element is not present in list.
// Java program to demonstrate search 
// operations on List interface 
import java.util.*; 

public class ListDemo 
{ 
	public static void main(String[] args) 
	{ 
		// Type safe array list, stores only string 
		List<String> l = new ArrayList<String>(5); 
		l.add("Geeks"); 
		l.add("for"); 
		l.add("Geeks"); 

		// Using indexOf() and lastIndexOf() 
		System.out.println("first index of Geeks:" + 
								l.indexOf("Geeks")); 
		System.out.println("last index of Geeks:" + 
							l.lastIndexOf("Geeks")); 
		System.out.println("Index of element"+ 
			" not present : " + l.indexOf("Hello")); 
	} 
} 

Output:

first index of Geeks:0
last index of Geeks:2
Index of element not present : -1

3 Iteration:
ListIterator(extends Iterator) is used to iterate over List element. List iterator is bidirectional iterator. For more details about ListIterator refer Iterators in Java.

4 Range-view:
List Interface provides a method to get the List view of the portion of given List between two indices. Following is the method supported by List for range view operation.

  • List subList(int fromIndex,int toIndex):This method returns List view of specified List between fromIndex(inclusive) and toIndex(exclusive).
// Java program to demonstrate subList operation 
// on List interface. 
import java.util.*; 
public class ListDemo 
{ 
	public static void main (String[] args) 
	{ 
		// Type safe array list, stores only string 
		List<String> l = new ArrayList<String>(5); 

		l.add("GeeksforGeeks"); 
		l.add("Practice"); 
		l.add("GeeksQuiz"); 
		l.add("IDE"); 
		l.add("Courses"); 

		List<String> range = new ArrayList<String>(); 

		// Return List between 2nd(including) 
		// and 4th element(excluding) 
		range = l.subList(2, 4); 

		System.out.println(range); 
	} 
} 

Output:

[GeeksQuiz, IDE]

This article is contributed by Dharmesh Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.

Custom ArrayList in Java

Prerequisite – ArrayList in Java
ArrayList in Java (equivalent to vector in C++) having dynamic size. It can be shrinked or expanded based on size. ArrayList is a part of collection framework and is present in java.util package.   ArrayList有动态大小,可以扩大或是缩小。
An ArrayList:

ArrayList <E> list = new ArrayList <> ();

E here represents an object datatype e.g. Integer. The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.
More about Integer Object: here
List Interface in Java with Examples
Custom ArrayList: A custom arraylist has attributes based on user requirements and can have more than one type of data. This data is provided by a custom inner class which is formed by combination of various primitive object datatypes.

Consider a case when we have to take input as N number of students and details are:
roll number, name, marks, phone number
A normal method using object arraylist would be:

   // define 4 ArrayLists and save data accordingly in
   // each of them.
    
   // roll number arraylist
   ArrayList<Integer> roll = new ArrayList<>(); 

   // name arraylist
   ArrayList<String> name = new ArrayList<>();

   // marks arraylist
   ArrayList<Integer> marks = new ArrayList<>();

   // phone number arraylist
   ArrayList<Long> phone = new ArrayList<>();

   // and for n students
   for(int i = 0; i < n; i++)
   {
     // add all the values to each arraylist 
     // each arraylist has primitive datatypes
     roll.add(rollnum_i);
     name.add(name_i);
     marks.add(marks_i);
     phone.add(phone_i);
  }

Now using a custom Arraylist:
The custom ArrayList simply supports multiple data in the way as shown in this image.
List Interface in Java with Examples
To construct Custom ArrayList

  • Build an ArrayList Object and place its type as a Class Data.
  • Define a class and put the required entities in the constructor.
  • Link those entities to global variables.
  • Data received from the ArrayList is of that class type which stores multiple data.
// Java program to illustrate customArraylist in Java 
import java.util.ArrayList; 

class CustomArrayList 
{ 
	// custom class which has data type 
	// class has defined the type of data ArrayList 
	// size of input 4 
	int n=4; 

	// the custom datatype class 
	class Data 
	{ 
		// global variables of the class 
		int roll; 
		String name; 
		int marks; 
		long phone; 

		// constructor has type of data that is required 
		Data(int roll, String name, int marks, long phone) 
		{ 
			// initialize the input variable from main 
			// function to the global variable of the class 
			this.roll = roll; 
			this.name = name; 
			this.marks = marks; 
			this.phone = phone; 
		} 
	} 

	public static void main(String args[]) 
	{ 
		// suppose the custom input data 
		int roll[] = {1, 2, 3, 4}; 
		String name[] = {"Shubham", "Atul", "Ayush", "Rupesh"}; 
		int marks[] = {100, 99, 93, 94}; 
		long phone[] = {8762357381L, 8762357382L, 8762357383L, 
						8762357384L 
					}; 

		// Create an object of the class 
		CustomArrayList custom = new CustomArrayList(); 

		// and call the function to add the values to the arraylist 
		custom.addValues(roll, name, marks, phone); 
	} 

	public void addValues(int roll[], String name[], int marks[], 
						long phone[]) 
	{ 
		// local custom arraylist of data type 
		// Data having (int, String, int, long) type 
		// from the class 
		ArrayList<Data> list=new ArrayList<>(); 

		for (int i = 0; i < n; i++) 
		{ 
			// create an object and send values to the 
			// constructor to be saved in the Data class 
			list.add(new Data(roll[i], name[i], marks[i], 
											phone[i])); 
		} 

		// after adding values printing the values to test 
		// the custom arraylist 
		printValues(list); 
	} 

	public void printValues(ArrayList<Data> list) 
	{ 
		// list- the custom arraylist is sent from 
		// previous function 

		for (int i = 0; i < n; i++) 
		{ 
			// the data received from arraylist is of Data type 
			// which is custom (int, String, int, long) 
			// based on class Data 

			Data data = list.get(i); 

			// data variable of type Data has four primitive datatypes 
			// roll -int 
			// name- String 
			// marks- int 
			// phone- long 
			System.out.println(data.roll+" "+data.name+" "
							+data.marks+" "+data.phone); 
		} 
	} 
} 

Output:

1 Shubham 100 8762357381
2 Atul 99 8762357382
3 Ayush 93 8762357383
4 Rupesh 94 8762357384

 

相关文章: