Java List Interface

 

Introduction

List Interface is the child interface of collection. The List interface is present in java.util package.

When we want to represent a group of individual objects in a single entity, where duplicates are allowed and insertion order preserved. Then we should go for the list interface.

In List Interface insertion Order is preserve and we can differentiate duplicate objects by using an index. That’s why the index is playing a very important role in the List.

 

 

Declaration of List Interface:

public abstract interface List extends Collection

 

There are several methods in the Java List Interface:

  • void add(int index, Object o) -> Using this method we can insert the specified element at the specified position in a list.                                                                                                                                                                                                         
  • boolean addAll(int index, Collection c) -> Using this method we can append all of the elements in the specified collection starting at the specified position of the list.                                                                                                                                              
  • Object get(int index) -> Using this method we can get the specifiec index element from list.                                           
  • Object remove(int index) -> Using this method we can delete the specifiec index element from list.                                     
  • Object set(int index, Object new) -> To replace the element present at the specified index with the provided object and returns the old object.                                                                                                                                                                                
  • int indexOf(Object o) -> Returns Index of 1ast Occurrence of ‘o’.                                                                                                            
  • int lastIndexOf(Object o) -> Using this method we can return the index in this list of the last occurrence of the specified element.                                                                                                                                                                                    
  • ListIterator listIterator() -> Using this method we can iterate the list od object.

 

ArrayList:

  • The underlying data structure for ArrayList and Vector is a resizable array growable array.
  • Duplicate objects are allowed in ArrayList and insertion order is preserved.
  • In ArrayList heterogeneous objects are allowed.
  • null Insertion is Possible in ArrayList.

 

Note: Except TreeSet and TreeMap everywhere heterogeneous objects are allowed.

 

ArrayList classes implement the RandomAccess interface. So that we can access any random element with the Same Speed.

RandomAccess Interface:

RandomAccess Interface Present in java.utilPackage and it doesn’t contain any methods, that’s why we are calling it is a Marker Interface.

ArrayList is the best choice if our frequent operation is retrieval operation. SO if we are want to search and get data from the list then ArrayList is the best option.

If our frequent operation is the insertion and deletion then it worsts choice, because when are deleting or adding any element in the list then shift operation is required and it takes too much time.

For insertion and deletion operation we need to use LinkedList.

 

How to create a different type of List Using ArrayList:

List<String> list = new ArrayList<String>(); //List of String type 

List<Integer> list = new ArrayList<Integer>(); //List of Integer type 

List<Student> list = new ArrayList<Student>(); //List of Student type

 

Constructors of ArrayList:

ArrayList list = new ArrayList();

  • Creates an Empty ArrayList Object with Default Initial Capacity 10.
  • Once ArrayList reaches its max capacity then a new ArrayList object will be created with a new capacity.

 

How to calculate new capacity:

New Capacity = (Current Capacity * 3/2) + 1

If the new current capacity is 10 then the new capacity is (10*3/2)+1=16 so the new capacity will be 16, so that’s we can find the new capacity of ArrayList.

 

ArrayList list = new ArrayList(intinitialCapacity);

In the above example, we are creating an empty ArrayList object with a specified initial capacity.

 

ArrayList list = new ArrayList(Collection c);

In the above example, we are creating an equivalent ArrayList object for the given collection object.

 

Example:

package com.technicalround.demo;
import java.util.ArrayList;
class ArrayListDemo1 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("Niraj");
list.add(99);
list.add("Kumar");
list.add(null);
System.out.println(list); // [Niraj, 99, Kumar, null]
list.remove(2);
System.out.println(list); // [Niraj, 99, null]
list.add(2, "Singh");
list.add("NKS");
System.out.println(list); // [Niraj, 99, Singh, null,NKS]
}
}

 

How to Convert in Synchronized Version of ArrayList Object?

Actually by default ArrayList object is Non-Synchronized but we can convert the synchronized version ArrayList by using the collections class of synchronizedList()method.

Syntex:

public static List synchronizedList(List l)

 

ArrayLista list = new ArrayList(); //Non-Synchronized of ArrayList Object
List list1 = Collections.synchronizedList(list); //Synchronized Version of ArrayList Object

 

How to convert List to Array:

package com.technicalround.demo;
import java.util.*;
public class Demo1 {
public static void main(String args[]) {
List<String> animal = new ArrayList<>();
animal.add("Dog");
animal.add("Cow");
animal.add("Cat");
animal.add("Monky");
// Converting ArrayList to Array using to toArray() method
String[] array = animal.toArray(new String[animal.size()]); 
System.out.println("Array of animal: " + Arrays.toString(array));
System.out.println("List of animal: " + animal);
}
}

OutPut:

Dog
Cow
Cat
Monky

 

How to convert Array to List:

package com.technicalround.demo;
import java.util.*;
public class Demo2 {
public static void main(String args[]) {
String[] array = { "One", "Two", "Five", "Six" };
System.out.println("Printing Array: " + Arrays.toString(array));
List<String> list = new ArrayList<String>();
for (String lang : array) {
list.add(lang);
}
System.out.println("Printing List: " + list);
}
}

Output:

Printing Array: [One, Two, Five, Six]
Printing List: [One, Two, Five, Six]

 

LinkedList:

  • The Underlying Data Structure of LinkedList is Double LinkedList.
  • In LinkedList insertion, the order is preserved and duplicate objects are not allowed.
  • Heterogeneous Objects are allowed.
  • In LinkedList null Insertion is Possible.
  • Implements Serializable and Cloneable Interfaces but not RandomAccess interface.
  • When our requirement is frequent operation is insertion or deletion in the middle of the list then LinkedList is the best choice, because we can easily connect one element node to another node.
  • If our requirement is frequent retrieval operation then LinkedList is the worst choice.

 

LinkedList Constructors:

LinkedList list = new LinkedList(); //We are creates an empty LinkedList object.
LinkedList list = new LinkedList(Collection c);//We are Creates an equivalent LinkedList object for the given collection.

 

LinkedList Method:

  • void addFirst(Object o) -> Using this method we can insert the given object at the starting of a list.                                                                                                                                                                                                        
  • void addLast(Object o) -> Using this method we can insert the given object at the last of a list.                                                                                                                                          
  • Object getFirst() -> Using this method we can get the first object of a list.                                                                                                                                
  • Object getLast() -> Using this method we can get the lat object of a list.                                                                                                                             
  • Object removeFirst() -> Using this method we can delete the given object at the starting of a list.                                                                                                                                                                              
  • Object removeLast() -> Using this method we can remove the given object at the last of a list.                                                                                                          
  • int size() -> Using this method we can get the size of a list.                                                                                                                                                                                  
  • Object get(int index) -> Using this method we can get the object at the specified position in a list.

 

LinkedList Example:

package com.technicalround.demo;
import java.util.*; 
public class LinkedListDemo{ 
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>(); 
al.add("INR"); 
al.add("EUR"); 
al.add("USD"); 
al.add("SGD"); 
Iterator<String> itr=al.iterator(); 
while(itr.hasNext()){ 
System.out.println(itr.next()); 
} 
} 
}

Output

INR
EUR
USD
SGD

 

Adding and Removing element in/from LinkedList

package com.technicalround;
import java.util.*;
public class Demo {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
System.out.println("Initial list of elements: " + list); //[]
list.add("INR");
list.add("USD");
list.add("INR");
list.add("SGD");
System.out.println("All adding element in list : " + list); //[INR, USD, INR, SGD]
list.remove("USD"); 
System.out.println("After removing element from list : " + list); // [INR, INR, SGD]
list.add(1, "USD");
System.out.println("All adding 2nd place element in list : " + list); //[INR, USD, INR, SGD]
list.remove(0);
System.out.println("After removing first postion element from list : " + list); //[USD, INR, SGD]
}
}

Output:

Initial list of elements: []
All adding element in list : [INR, USD, INR, SGD]
After removing element from list : [INR, INR, SGD]
All adding 2nd place element in list : [INR, USD, INR, SGD]
After removing first postion element from list : [USD, INR, SGD]

 

Example:

package com.technicalround;
import java.util.LinkedList;
class Demo {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("Niraj");
l.add(null);
l.add(99);
l.add("Niraj");
l.set(0, "Engineer");
l.add(0, "Kumar");
l.removeLast();
l.addFirst("Singh");
System.out.println(l); // [Singh, Kumar, Engineer, null, 99]
}
}

Output:

[Singh, Kumar, Engineer, null, 99]

 

Read More topics related to the collection.

 

 

Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.

 

 

Leave a Reply

Your email address will not be published.