Implementing Array Linear List in Java

Hey Folks,
In this tutorial, we will learn how to implement Array Linear List in Java and perform functions like add, delete and show in array linear list. So let’s begin. We write import java.util.* at the top of our file so it states that we import all the classes present in util package.

How to Implement Array Linear List in Java

Array list has the following functions which are in-built :

  • Add an element
  • Remove an element
  • Print the elements
import java.io.*; 
import java.util.*; 
class Arraylist 
{ 
    public static void main(String[] args) 
                       throws IOException 
    { 
        int n = 5; 
        ArrayList<Integer> arrli = new ArrayList<Integer>(n); 
        for (int i=1; i<=n; i++) 
            arrli.add(i); 
        System.out.println(arrli); 
        arrli.remove(3);  
        System.out.println(arrli); 
        for (int i=0; i<arrli.size(); i++) 
            System.out.print(arrli.get(i)+" "); 
    } 
}
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

First of all, we have made an object of ArrayList named arrli of integer wrapper class. And also we run a for loop to add a series of elements to our list. We simply write object.add(element) to add an element to our list. And object.remove(element) is written to delete an element present in our array list.

Secondly, we have used object.get(arrli) to print all the elements in our list. This programs only display how to add integers. So now let’s see how to add a string to our array list.

How to add String in Array List in Java

 

import java.util.*; 
class Array
{ 
    public static void main(String[] args) 
    { 
        // Creating a an ArrayList with String specified 
        ArrayList<String> al = new ArrayList<String> (); 
        al.add("CodeSpeedy"); 
        al.add("Utkarsh Tiwari"); 
        // Typecasting is not needed  
        String s1 = al.get(0); 
        String s2 = al.get(1); 
        System.out.println(s1);
        System.out.println(s2);
    } 
}
Output
CodeSpeedy
Utkarsh Tiwari

The new thing in the above program for strings is because we are now adding string to list we create object of string type. In array linear list we can add both numbers by running for loop and also add string values like your name in list all at the same time.

I hope you got concepts well, feel free to comment.

You may also read,

Leave a Reply

Your email address will not be published. Required fields are marked *