Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML


Java Tutorials



Struts Tutorials

Struts Resources

Visit Forum! Post Questions!
Jobs At RoseIndia.net!

Java Notes: ArrayList<E>

java.util.ArrayList<E> allows for expandable arrays, and is basically the same as the older the Collections Vector class. An ArrayList has these characteristics:

  • An ArrayList automatically expands as data is added.
  • Access to any element of an ArrayList is O(1). Insertions and deletions are O(N).
  • An ArrayList has methods for inserting, deleting, and searching.
  • An ArrayList can be traversed using a foreach loop, iterators, or indexes.

Arrays or ArrayList? Programmers are frequently faced with the choice of using a simple array or an ArrayList. If the data has a known number of elements or small fixed size upper bound, or where efficiency in using primitive types is important, arrays are often the best choice. However, many data storage problems are not that simple, and ArrayList (or one of the other Collections classes) might be the right choice.

Automatic expansion. Use ArrayList when there will be a large variation in the amount of data that you would put into an array. Arrays should be used only when there is a constant amount of data. For example, storing information about the days of the week should use an array because the number of days in a week is constant. Use an array list for your email contact list because there is no upper bound on the number of contacts.

Objects only. A possible disadvantage of ArrayList is that it holds only object types and not primitive types (eg, int). To use a primitive type in an ArrayList, put it inside an object or use of the wrapper classes (eg, Integer, Double, Character, ...). The wrapper classes are immutable, so if you use, eg, Integer, you will not be able to change the integer value. In this case it may be more useful to define your own mutable class.

Implementation. ArrayLists are implemented with an underlying array, and when that array is full and an additional element is added, a new, larger, array is allocated and the elements are copied from the old to the new. Because it takes time to create a bigger array and copy the elements from the old array to the new array, it is a slightly faster to create an ArrayList with a size that it will commonly be when full. Of course, if you knew the final size, you could simply use an array. However, for non-critical sections of code programmers typically don't specify an initial size.

Common ArrayList methods and constructors

Here are some of the most useful ArrayList methods. Assume these declarations.

   int i;
   ArrayList<E> a;
   E e;
   Iterator<E> iter;
   ListIterator<E> liter;
   E[] earray;
   Object[] oarray;
ResultMethod Description
anew ArrayList<E>() Creates ArrayList with initial default capacity 10.
anew ArrayList<E>(cap) Creates ArrayList with initial int capacity cap.
anew ArrayList<E>(coll<E>) Creates ArrayList from the Collection coll.
Adding elements
 a.add(e) adds e to end of ArrayList a
 a.add(i, e) Inserts e at index i, shifting elements up as necessary.
Replacing an element
 a.set(i,obj) Sets the element at index i to obj.
Getting the elements
obja.get(i) Returns the object at index i.
oarraya.toArray() Returns values in array of objects.
earraya.toArray(E[]) The array parameter should be of the E class. Returns values in that array (or a larger array is allocated if necessary).
itera.iterator() Returns an Iterator for forward traversal.
litera.listIterator(i) Returns a ListIterator for forward / backward / modifying traversal, starting at index i. Start from end with a.listIterator(a.size())
litera.listIterator() Returns a ListIterator for forward / backward / modifying traversal.
ba.contains(e) Returns true if ArrayList a contains e
ia.indexOf(e) Returns index of first occurrence of e, or -1 if not there.
ia.lastIndexOf(e) Returns index of last occurrence of e, or -1 if not there.
Removing elements
 a.clear() removes all elements from ArrayList a
 a.remove(i) Removes the element at position i.
 a.removeRange(i, j) Removes the elements from positions i thru j.
ia.size() Returns the number of elements in ArrayList a.

Adding elements to the end of an ArrayList, getting them by index

ArrayList<E> a = new ArrayList<E>();  // Default size.
T s;          // Declare s to be an object type T.
. . .
a.add(s);     // Adds s to the end of the ArrayList a
. . .
s = a.get(i); // Assigns ith element from a to s.

To get successive elements from an ArrayList

Use either a for loop with an integer index to get all the elements from an ArrayList, or go over all elements in a ArrayList using an Iterator (forward) or ListIterator (forward / backward).

  • foreach loop. This is fast and works for all kinds of lists, but is not entirely flexible (only sequential forward with no deletions, additions, or multiple references). This should be your first choice in programming. Works efficiently with both ArrayList and LinkedList.
    for (String s : a) {
  • for loop with index. This is fast, but should not be used with a LinkedList. It does allow orders other than sequentially forward.
    for (int i = 0; i < a.size(); i++) {
  • Iterator<E> - Allows simple forward traversal. Can be used for the largest number of other kinds of data structures.

    This example uses an Iterator to print all elements (Strings) in an ArrayList. It uses hasNext(), which returns true if there are more elements, and next(), which returns the next element. Works efficiently with both ArrayList and LinkedList.

    for (Iterator<String> iter = a.iterator(); iter.hasNext();) {
  • ListIterator<E> - Allows traversal of the ArrayList, but it is more general than a simple Iterator, allowing inserts and deletes (although both are very slow for an ArrayList). It also allows bidirectional traversal. Works efficiently with both ArrayList and LinkedList.


If the data in your ArrayList has a natural sorting order (ie, implements Comparable, as do String, Integer, ...), you can simply call the static Collections.sort() method. This is a stable, guaranteed n log n sort.


If you want to choose a different sort criterion or your data doesn't implement xxxx, you will have to define a Comparator and pass that to the sort() method.

Collections.sort(yourArrayList, yourComparator);

Check out Collections for other useful utility methods.

Ask programming questions?



Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

1 comments so far (post your own) View All Comments Latest 10 Comments:


Posted by Anju on Sunday, 03.1.09 @ 07:21am | #85348

  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name


Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright 2007. All rights reserved.

[an error occurred while processing this directive]