How to use ArrayList in Java

By Hong Viewed: 33766 times Emailed: 342 times Printed: 608 times Bookmark and Share



The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. In Java, standard 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. But, sometimes, you may not know until run time precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList. In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)

The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

The following program shows a simple use of ArrayList. An array list is created, and then objects of type String are added to it. (Recall that a quoted string is translated into a String object.) The list is then displayed. Some of the elements are removed and the list is displayed again.

// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}

The output from this program is shown here:

Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

Notice that a1 starts out empty and grows as elements are added to it. When elements are removed, its size is reduced.

Although the capacity of an ArrayList object increases automatically as objects are stored in it, you can increase the capacity of an ArrayList object manually by calling ensureCapacity( ). You might want to do this if you know in advance that you will be storing many more items in the collection that it can currently hold. By increasing its capacity once, at the start, you can prevent several reallocations later. Because reallocations are costly in terms of time, preventing unnecessary ones improves performance. The signature for ensureCapacity( ) is shown here:

void ensureCapacity(int cap)

Here, cap is the new capacity. Conversely, if you want to reduce the size of the array that underlies an ArrayList object so that it is precisely as large as the number of items that it is currently holding, call
trimToSize( )
, shown here:

void trimToSize( )

Obtaining an Array from an ArrayList

When working with ArrayList, you will sometimes want to obtain an actual array that contains the contents of the list. As explained earlier, you can do this by calling toArray( ). Several reasons exist why you might want to convert a collection into an array such as:

• To obtain faster processing times for certain operations.
• To pass an array to a method that is not overloaded to accept a collection.
• To integrate your newer, collection-based code with legacy code that does not understand collections.

Whatever the reason, converting an ArrayList to an array is a trivial matter, as the following program shows:

// get array
Object ia[] = al.toArray();
int sum = 0;
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}

The output from the program is shown here:
Contents of al: [1, 2, 3, 4]
Sum is: 10

The program begins by creating a collection of integers. As explained, you cannot store primitive types in a collection, so objects of type Integer are created and stored. Next, toArray( ) is called and it obtains an array of Objects. The contents of this array are cast to Integer, and then the values are summed.




Comments(46)


1. the superb way of making new concepts learn with ease.great

By: Ghulam MOhmad at 2008-09-18 23:43:42
2. Great guide. Missed the lecture, and this summed everything up in a quick and to the point manner.

By: Anonymous at 2008-12-21 19:36:19
3. great!
thanks to your guide i've just understand the ArrayList..great job!

By: Chris at 2009-02-14 02:24:28
4. I love http://www.java-samples.com very much , I was given and provided a very great and valuable knowledge

By: Phongveth at 2009-03-13 13:15:04
5. Excelente, y a pesar de que mi inglés no es muy bueno, he logrado al fín comprender lo que es un ArrayList. Muchas gracias.....

By: Monica at 2009-03-24 13:53:51
6. very simple explanation......
easily understandable code....
very much helpful for the students......

By: saurabh at 2009-04-17 16:02:30
7. Any thoughts on how conservative/liberal to be when specifying the initial capacity? Is it better to waste memory by allocating too much space or to spend resources recreating the array?

By: Jon at 2009-05-04 15:29:14
8. Hi Jon,

It really depends on the application. Roughly if you can gauge how many you would need, then it is best to assign initial capacity higher. However if you are using an old machine with less RAM, then you could consider the other option. But trust me there is no correct answer to this question.

By: Hong at 2009-05-04 20:40:28
9. Great tutorial about ArrayList .It's a very great and valuable knowledge for me.
I love java-samples for it's easily understandable code....
Thanks !





By: umesh sharma at 2009-05-14 20:40:39
10. Just what I needed. Thank you.

By: Clive Jefferies at 2009-06-01 08:05:15
11. My friend, How to user ArrayList?

By: Joao Neto at 2009-06-04 06:28:17
12. can i apply multidimensional array list the program!!
can you help me how to do this

By: aninostephen@uyahoo.com at 2009-07-01 05:09:27
13. what's the deffrint between "String[] [] ArrayList"
and thank u for this sit and i hop for u to go a head

By: ahmad at 2009-08-24 03:01:11
14. good work done.

By: Nitin at 2009-08-29 10:51:41
15. It's really helpful , thanks a lot

By: Avijit at 2009-09-08 05:18:39
16. What kind of elements can be stored in arraylist ?
Can i store calender ?

By: Himanshu at 2009-09-17 00:00:41
17. Bless you, bless you, bless you! You've kept me from failing my Java course! I wish professors and textbooks would use examples like these!

By: KRuthenberg at 2009-09-25 19:42:55
18. Cool it help me a lot

By: urdu sms at 2009-10-06 12:16:20
19. Thanx u m at lab..n u made me complete my prog!

By: Liza at 2009-12-09 23:03:51
20. wonderful
simplified description
keep it up!

By: ephrem at 2010-01-14 06:12:05
21. Nice code easily understand the code and useful

.....Satish

By: satish at 2010-01-22 06:30:22
22. how do i cast the contents of the arraylist to double???

By: ronnie at 2010-01-27 00:04:25
23. It was actually useful!!! Thanks for explaining in 5 min what my professor failed to explain in an hour's lecture.

By: steph at 2010-01-28 21:59:06
24. Good work, IT really help me a lot;

By: TUSHAR at 2010-02-03 01:25:37
25. I entered four different objects into an ArrayList using the add function.

when I want to list the contents as per your example, the most recent entry appears to occupy all four positions in the list.

This cannot be. Do you know what the source of the problem is?


By: ADC at 2010-02-25 18:43:32
26. Nice Work... Keep it..

By: Ashok at 2010-02-28 05:12:31
27. good but not best

By: VIVEK at 2010-03-09 03:00:21
28. very simple explanation

By: shahbaz at 2010-03-19 10:34:32
29. Wow thx, this is really easy for me to understand

By: brian at 2010-03-22 05:15:47
30. Nothing that hasn't been said before, but I wasn't paying attention when my teacher was talking about array lists, and this made it very clear and understandable.

By: Calvin at 2010-03-22 20:43:10
31. hey..
shouldn't the 2nd java code have an opening curly bracket { after the for loop condition??
right before the line:
sum += ((Integer) ia[i]).intValue();

By: izzie at 2010-04-06 11:34:34
32. i need save,delete,update use arrayList.
thank

By: kyaw at 2010-04-07 01:55:02
33. "Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList should be parameterized."
Can Somedy explain this warning for me please and advise how to aviod it.

By: WalterB Ntuli at 2010-04-09 01:51:17
34. It was sooo helpful for me
Thanx and keep it up
Good

By: Shan at 2010-04-13 09:41:01
35. Really superb.Simple code.Thanks.

By: pradesh at 2010-04-30 01:09:57
36. Good explaination, easy to understand
thanks

By: channaveer at 2010-05-02 05:03:21
37. M having query
i wat to create employee class with emp id,name,address.
i want to store some objects of this class in ArrayList. whn ian emp id is given then i should get emp's name & address.

M havng confusion tht ArrayList stores 1 object only thn how can V retrieve String's also wid tht Integer object.

reply me fast

By: Dayasagar at 2010-05-22 16:18:17
38. My Friend,

Thank you so much for explaining things concise but perfect.

By: Bikash at 2010-05-30 00:15:26
39. Wow Its awesome.
Thank you for giving such very very useful information.

By: sukumar maji at 2010-07-25 12:47:30
40. this is good arraylist

By: shaffy at 2010-07-31 04:25:17
41. thanku verymuch. very helpfull

By: praveen at 2010-08-05 06:04:35
42. Very well Explained Thank you Hog .

By: Asad at 2010-08-10 23:59:29
43. i like this site.good explanation,but it is good for beginners.


By: mamata at 2010-08-16 05:22:53
44. good going java samples

By: Rajesh at 2010-08-17 03:36:12
45. well written hog .good going

By: Rajesh at 2010-08-17 03:38:05
46. it is gooo...very helpful to know the basics

By: srikanth at 2010-08-24 00:38:57

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:


Enter Code:
The Captcha image

Latest Tutorials

[2010-09-02]Steps in using verisign certificate with Glassfish appserver
[2010-08-02]emulator 0 terminated while waiting for it to register!
[2010-08-02]Cannot run program "C:\Program Files\Java\jre6\bin\javac.exe": CreateProcess error=2, The system cannot find the file specified
[2010-08-01]Step by Step guide to setup freetts for Java
[2010-07-31]Speech Packages available for Java API
[2010-07-31]Tutorial on setting up freetts with maven
[2010-07-31]package com.sun.speech.freetts does not exist.
[2010-07-31]Text to Speech conversion program in Java
[2010-07-31]How to create wav file using freetts
[2010-07-31]How to set the width of a Text element in JavaFX?
[2010-07-31]Major components of FxObjects in JavaFX
[2010-07-03]Using the AWS SDK for Java in Eclipse
[2010-07-03]Using the AWS SDK for Java
[2010-01-01]Converting properties using PropertyEditors and Other Spring features worth mentioning
[2010-01-01]How to create an array and method in JSP

More Latest News

Most Viewed Articles (in last 30 days)
How to use ArrayList in Java
XML and Java - Parsing XML using Java Tutorial
How to use Iterator in Java
Using substring( ) in Java
How to Send SMS using Java Program (full code sample included)
FileReader and FileWriter example program in Java
indexOf( ) and lastIndexOf( ) in Java
Using StringTokenizer in Java
HashMap example in Java
wait(), notify() and notifyAll() in Java - A tutorial
Abstract classes in Java
Method Overriding in Java
compareTo( ) in Java
Method Overloading (function overloading) in Java
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Most Emailed Articles (in last 30 days)
Components of program
How to Send SMS using Java Program (full code sample included)
XML and Java - Parsing XML using Java Tutorial
Why java is important to the Internet
How to use ArrayList in Java
Execute system commands in a Java Program
FileReader and FileWriter example program in Java
Recursion in java
indexOf( ) and lastIndexOf( ) in Java
Method Overloading (function overloading) in Java
What is Java?
compareTo( ) in Java
History of Object
Sample Java Script that displays a movable clock
How to use Iterator in Java