Home  >  Forum  >  Core Java
Post New Query

Example of Java ArrayList class in Collection



Asked on February 22, 2015
Example of Java ArrayList class in Collection


Replied on February 22, 2015
Hi Ravi..

Java ArrayList class is part of collection in java. It is described as

  • Java ArrayList class uses a dynamic array for storing the elements.
  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
 

Example of Java ArrayList class


package programs;

import java.util.ArrayList;
import java.util.Iterator;

public class CollectionArrayList {
public static void main(String[] args) {
ArrayList <String> alist = new ArrayList <String> ();  // creating arraylist
alist.add("Atul"); // adding object in arraylist
alist.add("Diksha");
alist.add("Sunandana");
alist.add("Anand");
alist.add("Kumud");
Iterator <String> itr = alist.iterator(); //
while (itr.hasNext()){
System.out.println(itr.next());
}
}
}





Replied on February 22, 2015

How to synchronize ArrayList?


Replied on February 22, 2015
Instead of Iterator, traverse ArrayList elements using for-each loop.

import java.util.*;
public class MyArrayListTest {
public static void main(String[] args) {
ArrayList <String> al = new ArrayList <String>();
 al.add("Gracy");  
 al.add("Mark");  
 al.add("Antilla");  
 al.add("JoePork");
 
 for (String ob:al)
 System.out.println(ob);
}

}


Write Answer




©2019 concretepage.com | Privacy Policy | Contact Us