Java Programming | ArrayList Example

Join Programming and Development Chat Groups on Uphub.io

Introduction.

This is a tutorial for ArrayList in Java Programming. The ArrayList in nothing but the array of objects. ArrayList is easy to maintain. So lets see How to use ArrayList?…….

Program for ArrayList in Java.

//import Scanner and ArrayList as we require it.
import java.util.ArrayList;
import java.util.Scanner;
 
// the name of our class its public
public class ArrayListExample {
    //void main
        public static void main (String[] args)
        {
            //declare arraylist
            ArrayList<Integer> mylist= new ArrayList<Integer>();
            //scanner object
            Scanner input = new Scanner(System.in);
 
            //print a message
            System.out.println("How many elements in Array List do you want?");
            //get the input
            int a = input.nextInt();
            //declare a integer
            int no;
            System.out.println("Enter the Numbers");
            //a for loop to fill the array list
            for(int i=0;i<a;i++)
            {
                no = input.nextInt();
                mylist.add(no);
            }
 
            //you can add the element at any time
            //using this method
            mylist.add(12);
            //you can remove the element at any time
            //using this method
            //the element at 1st position will be removed
            mylist.remove(1);
 
            //a loop to print the array list
            for(int i=0;i<mylist.size();i++)
            {
                System.out.println("This Element at "+i+" position "+mylist.get(i));
            }
        }
}

Output

How many elements in Array List do you want?
5
Enter the Numbers
1
2
3
4
5
This Element at 0 position 1
This Element at 1 position 3
This Element at 2 position 4
This Element at 3 position 5
This Element at 4 position 12

How does it work

  1. You enter the elements.
  2. The elements are added in ArrayList.
  3. Some more are added and Removed.
  4. The ArrayList is printed.

Extending it

The program can be extended. This is a basic concept of java programming. You can Create the ArrayList by just changing the Type between < and >.

At the end.

You learnt creating the Java program for ArrayList. So now enjoy the program.

Please comment on the post and share it.

Sharing options: