Problem : Create a dynamic array that can add any number of elements of any object. Program :Step 1 - CodingCreate a text file c:\sunilos\TestArrayList.java and copy below contents./* * A program of array list. */ import java.util.*; public class TestArrayList { public static void main(String[] args) { ArrayList v = new ArrayList(); //You can insert any object in the ArrayList. Here it is string v.add("Ram"); v.add("Shyam"); v.add("Balram"); //Return type of get() method is Object. Object o = v.get(0); //You can insert any object in the ArrayList. Here it is Integer Integer i = new Integer(5);//Primitive data type need to be converted into Objects before inserting. v.add(i); //Type cast your object in desired Class Integer value = (Integer) v.get(3); System.out.println("3 value is " + value); //Get all elements and print System.out.println("Print All Elements with help of For loop "); for (int j = 0; j < v.size(); j++) { System.out.println(j + " : " + v.get(j)); } //Get all elements and print with help of Iterator interface Iterator it = v.iterator(); //Get an iteratorSystem.out.println("Print All Elements with help of Iterator "); while(it.hasNext()){ //Checks if any element in list Object oo = it.next(); //Get next available element System.out.println(" From Iterator -- " +oo); } } } Step 2 - Deployment
Step 3 - Testing
OutputC:\sunilos>java TestArrayListValue of Index # 3 = 5 Print All Elements with help of For loop 0 : Ram 1 : Shyam 2 : Balram 3 : 5 Print All Elements with help of Iterator From Iterator -- Ram From Iterator -- Shyam From Iterator -- Balram From Iterator -- 5 <<Previous | Next>> |