ArrayList is a dynamic data structure in which you can add or remove any number of elements and those elements are stored in ordered sequence. It may also contain duplicate values.
ArrayList are the implementations of List interface. The package you required to import the ArrayList is import java.util.ArrayList;
Syntax of ArrayList:
Its very easy to use ArrayList, below is the syntax to declare it:
ArrayList arrayListDemo = new ArrayListDemo();
String ArrayList Declaration:
ArrayList<String> arrayListDemo = new ArrayListDemo<String>();
By using this syntax, an ArrayList is created which you can use to store characters. Here arrayListDemo is the name of this particular ArrayList.
ArrayList Methods:
ArrayList is a subclass of AbstractList class and it implements List Interface. It has various methods that are defined and inherited from its parent class. Below is the list of those methods with example:
1. boolean add(Object o)
2. void clear()
3. Object clone()
4. boolean contains(Object element):
Example 1 ArrayList of Pre Definded Data types:
import java.util.*;
public class ArrayListDemo{
public static void main(String args[]){
//Step 1: Creating Objects of ArrayList
ArrayList<String> arraylist1= new ArrayList<String>();
ArrayList<Integer> arraylist2= new ArrayList<Integer>();
//Step 2: Adding Values
arraylist1.add("This");
arraylist1.add("is");
arraylist1.add("String");
arraylist1.add("arraylist");
arraylist2.add(1);
arraylist2.add(2);
arraylist2.add(3);
arraylist2.add(4);
//Step 3: Displaying all the values
System.out.println("String ArrayList : " +arraylist1);
System.out.println("Integer ArrayList : " +arraylist2);
}
}
Output:
String ArrayList : [This, is, String, arraylist] Integer ArrayList : [1, 2, 3, 4]
Comments
Post a Comment