Explain the ArrayList class in java with example

ArrayList class in Java

Definition

ArrayList is a predefined java class under java util package

Advantage

ArrayList is a generic dynamic array. Which means it can be of anytype or of any size

Some important methods of ArrayList class

Methods Purpose
add() It is used to add elements in ArrayList
size() It returns the size of ArrayList
isEmpty() It returns true if ArrayList is Empty, otherwise false
contains() It is used to search an element inside ArrayList and returns true if found, otherwise false
remove() It is used to delete an element from ArrayList

WAP in java to implement ArrayList and use the important mrthods like add(), size(),isEmpty() etc


import java.util.ArrayList;
class hunteye {
    public static void main(String[] args) {
      ArrayList obj = new ArrayList();
      // isEmpty() will return true here as obj is empty 
      System.out.println(obj.isEmpty()); // true
      //size() will return 0
       System.out.println(obj.size()); //0
       // adding int
       obj.add(12);
       // adding float
       obj.add(567.123);
       //adding char
       obj.add('$');
       //adding string 
       obj.add("Java is OOPS");
       //printing all element
       System.out.println(obj);
        // isEmpty() will return false here as obj is not empty 
      System.out.println(obj.isEmpty()); // false
     //size() will return 4
       System.out.println(obj.size()); //4
      //contains(12) will return true
      System.out.println(obj.contains(12)); 
      //remove() to remove  element from ArrayList 
      obj.remove(0);// deleting element from 0 Position
      //printing all element
      System.out.println(obj);
    }
}

Output

true
0
[12, 567.123, $, Java is OOPS]
false
4
true
[12, $, Java is OOPS]

Share:

0 Comments:

Post a Comment

Pageviews