Showing posts with label Class. Show all posts
Showing posts with label Class. Show all posts

Friday, June 17, 2016

ArrayList Class Collection example java

ArrayList Class

An ArrayList is like an array, which can grow in memory dynamically.Memory is dynamically allotted and re-allotted to accommodate all the elements. ArrayList is not synchronized. Un-reliable result in case of multi threading.

Default Initial Capacity: 10
Load Factor=0.75

ArrayList Class Methods


  • boolean add(element obj)
  • void add(int position,element obj)
  • element remove(int position)
  • boolean remove(object obj)
  • void clear()
  • element set(int position,element obj)
  • boolean contains(Object obj)
  • element get(int position)
  • int indexOf(Object obj)
  • int lastIndexOf(Object obj)
  • int size()
  • Object[] toArray()

Program:


/**
 * 
 */
package com.collectionpack;

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

/**
 * @author Abhinaw.Tripathi
 *
 */
public class ArrayListDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> list=new  ArrayList<>();
list.add("Apple");
list.add("Mango");
list.add("Grapes");
list.add("Guava");
System.out.println("Contents= :" +list);
System.out.println("List size is :" +list.size());
System.out.println("Extracting from the list:");
Iterator it=list.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}

}

Output:


Contents= :[Apple, Mango, Grapes, Guava]

List size is :4
Extracting from the list:
Apple
Mango
Grapes
Guava