List Interface in Java with Examples

In this article, we will learn about the List Interface in Java with Examples.

The List interface provides a way to save the ordered collection. It is a child interface of Collection. It is an ordered collection of objects that can be used to store duplicate values. Because List maintains the order in which it is inserted, it allows location access and the insertion of items.

Declaration

public abstract interface List extends Collection ; 

Let’s dive deeper into the creation of objects or instances in a List class. Because List is an interface, List objects cannot be created. We still need a class that extends this list to create an object. In addition, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be registered in the list.

Syntax

List<Obj> list = new ArrayList<Obj> (); 

Example

import java.util.*;

class HandyOpinion{

	public static void main(String[] args)
	{
		// Creating an object of List class
		List<Integer> l1 = new ArrayList<Integer>();
		l1.add(10, 20);
		l1.add(20, 30);

		// Print the elements inside the object
		System.out.println(l1);

		// Now creating another List class object
		List<Integer> l2 = new ArrayList<Integer>();

		// Again adding elements to object of List class
		// Custom inputs
		l2.add(10);
		l2.add(20);
		l2.add(30);

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

		System.out.println(l1);

		// Removes element from index 1
		l1.remove(1);

		// Printing the updated List 1
		System.out.println(l1);

		// Prints element at index 3 in list 1
		// using get() method
		System.out.println(l1.get(3));

		// Replace 0th element with 50
		// in List 1
		l1.set(0, 50);

		// Again printing the updated List 1
		System.out.println(l1);
	}
}

Output

[10, 20]
[10, 10, 20, 30, 20]
[10, 20, 30, 20]
20
[50, 20, 30, 20]

That’s all, we will learn about the List Interface in Java with Examples.

Next Article

1. PriorityQueue in Java
2. Stack Class in Java
3. Queue Interface In Java

Please share this post:
Posts created 69

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: