Java - ArrayList

The class java.util.ArrayList provides resizable-array, which means that items can be added and removed from the list.Java ArrayList class can contain duplicate elements, including null.
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.

ArrayList common methods:

Method Description
boolean add(Element e) Adds the specified element to end of this list.
void clear() Removes all the elements from the list.
int size() Returns the length of the list (the number of elements contained in the list).
Object get(int index) Returns the element at the specified position in this list

Example :

							  
import java.util.ArrayList;

public class ArrayListEx {
	public static void main(String[] args) {
		
		//Ex 1 : String of Elements in Java ArrayList
		ArrayList<String> al=new ArrayList<String>();
		al.add("C");
		al.add("C++");
		al.add("Java");
		al.add("Android");
		
		System.out.println("+++++++++ Print Elements using for loops ++++++++++++");
		
		for(int i=0;i<al.size();i++){
			System.out.println(al.get(i));
		}
		
		System.out.println("+++++++++ Print Elements using for-each loops ++++++++++++");
		for(String str:al){
			System.out.println(str);
		}
		
		//Ex 2 : User-defined class objects in Java ArrayList
		 //Creating user-defined class objects  
		  Student s1=new Student(101,"XXX",23);  
		  Student s2=new Student(102,"YYY",24);  
		  Student s3=new Student(103,"ZZZ",25);  
		      
		  ArrayList<Student> al1=new ArrayList<Student>();//creating arraylist  
		  al1.add(s1);//adding Student class object  
		  al1.add(s2);  
		  al1.add(s3);
		  
		  System.out.println("+++++++++ Print User-defined class objects using for-each loops ++++++++++++");
			for(Student str:al1){
				System.out.println("Name : "+str.name+" RollNo : "+str.rollno+" Age : "+str.age);
			}
	}
}

							  

OUTPUT :

							  
+++++++++ Print Elements using for loops ++++++++++++
C
C++
Java
Android
+++++++++ Print Elements using for-each loops ++++++++++++
C
C++
Java
Android
+++++++++ Print User-defined class objects using for-each loops ++++++++++++
Name : XXX RollNo : 101 Age : 23
Name : YYY RollNo : 102 Age : 24
Name : ZZZ RollNo : 103 Age : 25
							  
							  

BytecodeTechnosolutions.com | Raju