Arraylist in Java

Ratings:
(4)
Views: 0
Banner-Img
Share this blog:

Arraylist in java

An ArrayList is a dynamic data structure, meaning items can be added and removed from the list. A normal array in java is a static data structure, because you stuck with the initial size of your array.
 

 

What is the ArrayList in Java?

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.

Example

The following program illustrates several of the methods supported by ArrayList −
import java.util.*;
public class ArrayListDemo {
   public static void main(String args[]) {
      // create an array list
      ArrayList al = new ArrayList();
      System.out.println("Initial size of al: " + al.size());
      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");
      al.add(1, "A2");
      System.out.println("Size of al after additions: " + al.size());
      // display the array list
      System.out.println("Contents of al: " + al);
      // Remove elements from the array list
      al.remove("F");
      al.remove(2);
      System.out.println("Size of al after deletions: " + al.size());
      System.out.println("Contents of al: " + al);
   }
}
This will produce the following result −

Output

Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

Arraylist Methods

  • Arraylist add: This is used to add elements to the Array List. If an ArrayList already contains elements, the new element gets added after the last element unless the index is specified.
  • Arraylist remove: The specified element is removed from the list and the size is reduced accordingly. Alternately, you can also specify the index of the element to be removed.
  • Java array size:  This will give you the number of elements in the Array List. Just like arrays, here too the first element starts with index 0.
  • Arraylistcontains:  This method will return true if the list contains the specified element.

User-defined class objects in Java ArrayList

class Student{  
 int rollno;  
  String name;  
  int age;  
  Student(int rollno,String name,int age){  
   this.rollno=rollno;  
   this.name=name;  
   this.age=age;  
}  
}  
import java.util.*;  
public class TestCollection3{  
 public static void main(String args[]){  
  //Creating user-defined class objects  
  Student s1=new Student(101,"Sonoo",23);  
  Student s2=new Student(102,"Ravi",21);  
  Student s2=new Student(103,"Hanumat",25);        
  ArrayList<Student> al=new ArrayList<Student>();//creating arraylist  
  al.add(s1);//adding Student class object  
  al.add(s2);  
  al.add(s3);      
  Iterator itr=al.iterator();  
  //traversing elements of ArrayList object  
  while(itr.hasNext()){  
    Student st=(Student)itr.next();  
    System.out.println(st.rollno+" "+st.name+" "+st.age);  
 }  
 }  
}

The ArrayList data structure

The array is the fundamental data structure built into Java for holding collections of items. Arrays provide two basic operations: You can retrieve the value at an index, or you can change the value at an index. These are quite similar to the List ADT's get and set operations.
array operation equivalent List ADT operation
x = data[i]; x = get(i)
data[i] = x; set(ix)
This similarity is what inspires the implementation of the List interface using an array to store the data elements. There are other List operations that don't correspond to anything we can do with an array (add and remove); but this is a detail that we can hope to overcome. Overall, it seems like an array is a good candidate for implementing the List interface. Java's built-in libraries already include such an implementation; specifically, the java.util package includes the ArrayList class. To use it, you need to include a import statement at the top of your program definition.
import java.util.ArrayList;
 
Like the List interface, the ArrayList class is a generic. Inside a method definition, we can declare a names variable and then assign it to refer to a newly created ArrayList object.
List<Stringnames;
 names = new ArrayList<String>();
 
Once we have a way of referring to an ArrayList object, then we can tell it to do things using the ArrayList methods, which necessarily include all the methods in the List interface. Among these is the add method.
names.add("Martin");
 names.add("Galloway");
 
Suppose we want to display all the strings in the ArrayList. List's size and get methods are useful for this.
for(int i = 0; i < names.size(); i++) {
     System.out.println(names.get(i));
 }

Implementing the ArrayList in Java

implement an arraylist.add() method using nothing but arrays and an array copy method but im having trouble doing it . The specification of the method is that the method inserts an element at a specified position and shifts any of the elements currently in the position to the right and add one to the indices expanding the size of the array by one so all elements fit . Someone please help .
    private Object [] list;
    final int maxObjects = 100;
    public ListOfObjects()
    {
        list= new Object[maxObjects];
    }
    public ListOfObjects(Object[]o)
    {
        list= o;
    }
    public void add(Object element,int index)
    {
        Object[] newData = new Object[list.length+1];
        for(int i =0; i < index; i++)
        {
            newData[i] = list[i];
            newData[list] = element;
        }
        for(int i = index; i < list.length; i++)
        {
     newData[i+1] = list[i];
        }
    }

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox