Write a Program to Create a List in Java? with Algorithm and Source Code

List Interface in Java with Examples

Aim:

To write a java program for creating a list.

The Java.util. The 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.

Algorithm for Java List:

  1. List Interface is the subinterface of Collection.
  2. It contains index-based methods to insert and delete elements.
  3. It is a factory of ListIterator interface.
  4. List<String> al = new ArrayList<String>();    
  5. al.add(“Amit”);    
  6. al.add(“Vijay”);    
  7. al.add(“Kumar”);    
  8. al.add(1,”Sachin”);    
  9. ListIterator<String> itr=al.listIterator();    

Source Code:

// 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);
}
}
Write a java program for creating list

FAQ:

How do you declare a list in Java?

In java, we can declare a list by following way:
List<Integer> l1 = new ArrayList<Integer>();

What are the list methods in Java?

The list methods in java are:
int size()
boolean isEmpty()
boolean contains(Object o)
iterator iterator()
object[] toArray()
boolean add(E e)
boolean remove(Object o)
boolean retainAll(Collection c)
void clear()
E get(int index)

How do I search a list in Java?

To search object from the list in java using the method contains(). It will return True when the object is available in a list if not available then it will return False.

Is ArrayList same as list Java?

ArrayList is a Class. ArrayList is present in java.util package. It provides us with a dynamic array. The size of ArrayList is increased automatically if the size of the list increase or the list removes.
The list is as Interface. List interface extends the size of the frame. The list can not be instantiated. List interface creates a group of elements that store the sequence of the element.

Recommended Post:

Find the solution to the salesforce Question and many more

Hi, I’m Pramod Kumar Yadav & a computer science Engineer with 3years of experience in Digital marketing. I’m self-motivated and love to do SEO.

Leave a Reply

%d bloggers like this: