Skip to main content

List interface in java with examples

Read this article to know what is List interface and what are the List implemented classes in java with example programs.  List interface  represents a group of elements arranged like an array in java. List will grow dynamically when the elements are stored into it. List will allow duplicate elements to store into it. List interface implemented classes are,
  •  ArrayList<E>
  • Vector<E>
  • LinkedList<E>
          < E > represents the genetic type of storing element into List.

List interface methods:
The below are the list of methods which are available in List Interface. These methods are also available in subclasses of the List interface.
  •   void add(int position, element obj): Adds the second argument into the List at the index specified by the first argument.
  •   void add(element obj): This method appends the specified element to the end of the ArrayList. If the element is added successfully then the preceding method returns true.
  • Object get( int position): Returns the element at the index specified by the argument.
  • int indexOf(Object obj): Returns the index of the element specified by the argument or -1 if the element was not found.
  • int lastindexOf(Object obj): Returns the last index of the element specified by the argument or -1 if the element was not found.
  • Listlterator listlterator( ): Returns a Listlterator object representing the items in this List.
  • Listlterator listlterator( int position): Returns a Listlterator object representing the items in this List starting with the index specified by the argument.
  • Object remove( int position): Returns the element at the index specified by the argument and removes it from the List.
  • Object set( int position, Object obj): Returns the element found at the index specified by the first argument and replaces it with the second argument.
  • int size(): this method returns the no.of elements present in the list.
  • Object[] toArray: This method returns an Object array containing all the elements in list in proper sequence.
  • boolean contains(Object obj): This method returns true if the list contains the specified element obj.
ArrayList:
ArrayList is an dynamic array, which can grow dynamically. ArrayList is fail-fast and not thread safe, because it is not synchronized by default. So, ArrayList will work faster than the Vector but may not provide correct results at the time of multithread access. ArrayList default size is 10 to store elements into it.

The ArrayList class can be written as,
class ArrayList<E>
         
Where E represents the type of elements to be stored into the ArrayList. For example to store String type elements, we can create an object to ArrayList as,
 ArrayList<String> arl = new ArrayList<String>();

Ex: Here is the example of how to create an arrayList and perform various operations on it.
package com.javatbrains.collections;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListDemo {

     public static void main(String[] args) {
          //Create an ArrayList
          List<String> al = new ArrayList<String>();
         
          //Add few of String type of elements
          al.add("Apple");
          al.add("Mango");
          al.add("Sapota");
          al.add("Grapes");
         
          //Display all fruits
          System.out.println("Fruits are: "+al);
         
          //Remove Two fruit names from list
          al.remove(3);
          al.remove("Apple");
          //Display again all fruits
          System.out.println("Remaining Fruits are: "+al);
         
          //Display the size of the arrayList
          System.out.println("Size is: "+al.size());
         
          //Extract elements using Iterator
          System.out.println("Extract elements: ");
         
          //Add an iterator to ArrayList to retrieve elements
          Iterator<String> it = al.iterator();
          while(it.hasNext()){
              System.out.println(it.next());
          }
     }

}
OutPut:
     Fruits are: [Apple, Mango, Sapota, Grapes]
                  Remaining Fruits are: [Mango, Sapota]
                  Size is: 2
                  Extract elements:
                  Mango
                  Sapota

Vector class:
A Vector also stores elements similar to ArrayList, but Vector is synchronized. It means even if several threads act on simultaneously, the results will be reliable. Vector class default size also 10. When elements storing reaching to last element, Vector memory size will be doubled. We can write a Vector class as,
class Vector<E>

Here E represents the type of element stored into the Vector. For example, when we are trying to store the Integer objects into Vector,
Vector<Integer> v = new Vector<Integer>();

The below capacity method Vector class contains an extra operation, remaining all methods as same as the above mentioned methods in Vector. These all methods are thread-safe because, Vector class is synchronized.
  • int capacity(): This method returns the current capacity of the Vector.
Ex: Here is the example to show the use of Vector class.
package com.javatbrains.collections;

import java.util.ListIterator;
import java.util.Vector;

public class VectorDemo {

     public static void main(String[] args) {
          // Create a Vector object to store Integer objects
          Vector<Integer> v = new Vector<Integer>();
          // take an int type array
          int arr[] = { 21, 51, 24, 23, 45, 10 };

          /*
           * When arr[i] is stored into v below. arr[i]
           * values are converted into Integer objects
           * and stored into v. This is Autoboxing.
           */
          for(int i=0;i<arr.length;i++){
              v.add(arr[i]);
          }
         
          //retrieve elements by using get()
          System.out.println("Vector elements are: ");
          for(int i=0;i<v.size();i++){
              System.out.println(v.get(i));
          }
         
          //Retrieve using ListIterator
          System.out.println("Elements using ListIterator:");
          ListIterator<Integer> li = v.listIterator();
          System.out.println("In Forward direction: ");
          while(li.hasNext()){
              System.out.print(li.next()+"\t");
          }
         
          System.out.println("\nIn Backward direction: ");
          while(li.hasPrevious()){
              System.out.print(li.previous()+"\t");
          }
     }

}
OutPut:
     Vector elements are:
          21
          51
          24
          23
          45
          10
          Elements using ListIterator:
          In Forward direction:
          21   51   24   23   45   10  
          In Backward direction:
          10   45   23   24   51   21  

LinkedList class:
A LinkedList contains a group of elements in the form of nodes. Each node will have 3 fields- the data field contains data and the link fields contains reference to previous and next nodes.
         
Node structure:         
    link
      data
    link
                            
Linked list is very convenient to store data. Inserting the elements into the linked list and removing the elements from the linked list is done quickly and takes the same amount of time.

A LinkedList is written in the form of:
class LinkedList<E>  

We can create empty LinkedList for storing String type of elements,
LinkedList<String> ll = new LinkedList<String>();

Methods of LinkedList:
LinkedList contains few of the extra methods compare to ArrayList and Vector. They are,
  •   void addFirst(Object): Adds the argument to the beginning of the list.
  •   void addLast(Object): Adds the argument to the end of the list.
  •   Object getFirst( ): Gets the first element from the list.
  • Object getLast( ): Gets the last element from the list.
  •   Object removeFirst( ): Returns the first element from the list and removes it from the list.
  • Object removeLast( ): Returns the last element from the list and removes it from the list.

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...