How to use ArrayList in Java

By: Hong Emailed: 1646 times Printed: 2112 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(74)


1. View Comment

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

View Tutorial          By: Ghulam MOhmad at 2008-09-18 23:43:42
2. View Comment

Great guide. Missed the lecture, and this summed everything up in a quick and to the point manner.

View Tutorial          By: Anonymous at 2008-12-21 19:36:19
3. View Comment

great!
thanks to your guide i've just understand the ArrayList..great job!


View Tutorial          By: Chris at 2009-02-14 02:24:28
4. View Comment

I love http://www.java-samples.com very much , I was given and provided a very great and valuable knowledge

View Tutorial          By: Phongveth at 2009-03-13 13:15:04
5. View Comment

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.....

View Tutorial          By: Monica at 2009-03-24 13:53:51
6. View Comment

very simple explanation......
easily understandable code....
very much helpful for the students......


View Tutorial          By: saurabh at 2009-04-17 16:02:30
7. View Comment

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?

View Tutorial          By: Jon at 2009-05-04 15:29:14
8. View Comment

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.


View Tutorial          By: Hong at 2009-05-04 20:40:28
9. View Comment

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 !


View Tutorial          By: umesh sharma at 2009-05-14 20:40:39
10. View Comment

Just what I needed. Thank you.

View Tutorial          By: Clive Jefferies at 2009-06-01 08:05:15
11. View Comment

My friend, How to user ArrayList?

View Tutorial          By: Joao Neto at 2009-06-04 06:28:17
12. View Comment

can i apply multidimensional array list the program!!
can you help me how to do this


View Tutorial          By: aninostephen@uyahoo.com at 2009-07-01 05:09:27
13. View Comment

what's the deffrint between "String[] [] ArrayList"
and thank u for this sit and i hop for u to go a head


View Tutorial          By: ahmad at 2009-08-24 03:01:11
14. View Comment

good work done.

View Tutorial          By: Nitin at 2009-08-29 10:51:41
15. View Comment

It's really helpful , thanks a lot

View Tutorial          By: Avijit at 2009-09-08 05:18:39
16. View Comment

What kind of elements can be stored in arraylist ?
Can i store calender ?


View Tutorial          By: Himanshu at 2009-09-17 00:00:41
17. View Comment

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!

View Tutorial          By: KRuthenberg at 2009-09-25 19:42:55
18. View Comment

Cool it help me a lot

View Tutorial          By: urdu sms at 2009-10-06 12:16:20
19. View Comment

Thanx u m at lab..n u made me complete my prog!

View Tutorial          By: Liza at 2009-12-09 23:03:51
20. View Comment

wonderful
simplified description
keep it up!


View Tutorial          By: ephrem at 2010-01-14 06:12:05
21. View Comment

Nice code easily understand the code and useful

.....Satish


View Tutorial          By: satish at 2010-01-22 06:30:22
22. View Comment

how do i cast the contents of the arraylist to double???

View Tutorial          By: ronnie at 2010-01-27 00:04:25
23. View Comment

It was actually useful!!! Thanks for explaining in 5 min what my professor failed to explain in an hour's lecture.

View Tutorial          By: steph at 2010-01-28 21:59:06
24. View Comment

Good work, IT really help me a lot;

View Tutorial          By: TUSHAR at 2010-02-03 01:25:37
25. View Comment

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?


View Tutorial          By: ADC at 2010-02-25 18:43:32
26. View Comment

Nice Work... Keep it..

View Tutorial          By: Ashok at 2010-02-28 05:12:31
27. View Comment

good but not best

View Tutorial          By: VIVEK at 2010-03-09 03:00:21
28. View Comment

very simple explanation

View Tutorial          By: shahbaz at 2010-03-19 10:34:32
29. View Comment

Wow thx, this is really easy for me to understand

View Tutorial          By: brian at 2010-03-22 05:15:47
30. View Comment

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.

View Tutorial          By: Calvin at 2010-03-22 20:43:10
31. View Comment

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();


View Tutorial          By: izzie at 2010-04-06 11:34:34
32. View Comment

i need save,delete,update use arrayList.
thank


View Tutorial          By: kyaw at 2010-04-07 01:55:02
33. View Comment

"Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList<E> should be parameterized."
Can Somedy explain this warning for me please and advise how to aviod it.


View Tutorial          By: WalterB Ntuli at 2010-04-09 01:51:17
34. View Comment

It was sooo helpful for me
Thanx and keep it up
Good


View Tutorial          By: Shan at 2010-04-13 09:41:01
35. View Comment

Really superb.Simple code.Thanks.

View Tutorial          By: pradesh at 2010-04-30 01:09:57
36. View Comment

Good explaination, easy to understand
thanks


View Tutorial          By: channaveer at 2010-05-02 05:03:21
37. View Comment

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


View Tutorial          By: Dayasagar at 2010-05-22 16:18:17
38. View Comment

My Friend,

Thank you so much for explaining things concise but perfect.


View Tutorial          By: Bikash at 2010-05-30 00:15:26
39. View Comment

Wow Its awesome.
Thank you for giving such very very useful information.


View Tutorial          By: sukumar maji at 2010-07-25 12:47:30
40. View Comment

this is good arraylist

View Tutorial          By: shaffy at 2010-07-31 04:25:17
41. View Comment

thanku verymuch. very helpfull

View Tutorial          By: praveen at 2010-08-05 06:04:35
42. View Comment

Very well Explained Thank you Hog .

View Tutorial          By: Asad at 2010-08-10 23:59:29
43. View Comment

i like this site.good explanation,but it is good for beginners.

View Tutorial          By: mamata at 2010-08-16 05:22:53
44. View Comment

good going java samples

View Tutorial          By: Rajesh at 2010-08-17 03:36:12
45. View Comment

well written hog .good going

View Tutorial          By: Rajesh at 2010-08-17 03:38:05
46. View Comment

it is gooo...very helpful to know the basics

View Tutorial          By: srikanth at 2010-08-24 00:38:57
47. View Comment

Thanks summarized and useful

View Tutorial          By: Pegasus_Silvershade at 2010-09-10 18:02:49
48. View Comment

Very good explanation along with the example. Can understand easily...

View Tutorial          By: Divya at 2010-09-21 03:05:10
49. View Comment

Thankyou very much for the explanation

View Tutorial          By: Ruchita at 2010-11-11 01:16:10
50. View Comment

Good Job.
Keep up the good work .


View Tutorial          By: Syed Imran at 2010-11-27 06:54:36
51. View Comment

i want my program to allow more than one traineeâs marks to be entered, and then print the results for each trainee at the
end of the program, rather than after each traineeâs marks have been entered.i got stuck and need your help


import java.util.Scanner;
public class InstructionalModulesResult {
private static int firstint,intModuleQuizMark, noOfQuiz;
private static String lastString, fistString,stringMode;
private static double [] QuizMark;
static char letterGrade;
public static void main(String[] args) {
boolean vinto=true;
String ans;
int tNum=0, nOfQuiz;
double [] quizMark;
double finalModule, avgMark, sumMark=0, overallMark;
String famName, firName, instModule;
char markGrade;
boolean found=false;
Scanner in = new Scanner(System.in);
Scanner inStr = new Scanner(System.in);
for(int i=1;(!found);i++)
{
System.out.print("Trainee Number: ");
tNum=in.nextInt();
if ((tNum<=1000) || (tNum>=9999))
System.out.println("Invalid Number - Please re-enter ");
else
found=true;
}
System.out.print("Family Name: ");
famName =inStr.nextLine();
System.out.print("First Name: ");
firName =inStr.nextLine();
System.out.print("Instruction Module: ");
instModule =inStr.nextLine();
System.out.print("How many quizes shall i calculate?: ");
nOfQuiz =in.nextInt();
quizMark = new double [nOfQuiz];
for(int k=0; k<nOfQuiz;k++)
{
System.out.print("Module Quiz mark "+(k+1)+": ");
tNum=in.nextInt();
if ((tNum<=1) || (tNum>=100))
System.out.println("invalid Quiz mark, please re-enter a valid quiz mark not above 100");
else
found=true;
quizMark[k]=in.nextDouble();
}
System.out.print("Final Module Test mark: ");
finalModule = in.nextDouble();

System.out.print("Another [Y/N]?");
ans=in.nextLine();
if(ans=="Y")vinto=true;

else
vinto=false;
{
for (int k=0; k<nOfQuiz; k++)
{
sumMark = sumMark + quizMark[k];
}
avgMark =(sumMark)/nOfQuiz;
overallMark = (avgMark*0.20)+(finalModule*0.80);
markGrade = grade(overallMark);
System.out.println("Results for " + firName+" "+famName);
System.out.println("Trainee Number " + tNum);
System.out.println("Module: " + instModule);
System.out.println("Average Module Quiz: " + avgMark +" Final Module Test: " + finalModule+ " Overall Mark: " +overallMark);
System.out.println("Letter Grade: " + markGrade);
}
}

private static char grade (double graded) {
if (graded>=70)
letterGrade = 'A';
else if (graded>=60)
letterGrade = 'B';
else if (graded>=50)
letterGrade = 'C';
else if (graded>=40)
letterGrade = 'D';
else if (graded<=39 )
letterGrade = 'E';
return letterGrade;



}
}


View Tutorial          By: carl at 2011-01-30 22:21:21
52. View Comment

Thanks, I understand the add function better now (found out it will expand the size as it needs).

However, I noticed that you didn't set the capacity of ArrayList al during the initiation. According to the API, the default size of an ArrayList is 10. But on your output, it says 0, are you sure nothing is missing on the code?

Thanks again


View Tutorial          By: Venus at 2011-02-11 09:09:55
53. View Comment

Thanks a lot of!! at last I understood how use ArrayList in Java, great job!
regards from Acapulco Mexico


View Tutorial          By: Juan Carlos Aviles at 2011-03-11 05:22:03
54. View Comment

Muchas gracias por tu codigo. Me ayudo a resolver un problema que tenia con listas, al querer convertir un decimal a romano.

Object numerosEnteros[] = numeros.toArray();
System.out.println("\nSalida");
for(int i=0; i<numerosEnteros.length; i++){
int numEntero = ((Integer) numerosEnteros[i]).intValue();
if(numEntero!=0){
String rom = RomanConversion.binaryToRoman(numEntero);
System.out.println(numEntero+""+"\t"+rom);
}
}


View Tutorial          By: David Nava at 2011-04-08 03:29:38
55. View Comment

Thanks,
But i would like to use an array list as parameter for a constructor of other class, using this interface as parameter worked in methods but not for a constructor, why?

List<base_class> my_var


View Tutorial          By: Gustavo at 2011-06-15 21:03:20
56. View Comment

can't understand........

View Tutorial          By: james at 2011-06-23 02:44:22
57. View Comment

good

View Tutorial          By: pardhuman at 2011-06-24 08:18:15
58. View Comment

array is the one which can save similar data typed elements.
And the size is limited.
arraylist is a collection which is capable of saving
different data typed objects,And is growable.


View Tutorial          By: Cegonsoft Reviews at 2011-07-26 00:54:18
59. View Comment

nice one !!! just keep it .. i have learn a lot.. hoping next time you can help me again !

View Tutorial          By: dondon at 2011-07-27 04:43:40
60. View Comment

Showing code with quote tags is pretty rubbish. :/ But thanks anyway

View Tutorial          By: Daniel Jonsson at 2011-09-01 14:01:04
61. View Comment

Daniel Jonsson, you should be thankful to this article instead! this article got in the mind for readers and explained the concept to the readers, wonderful!
Thanks!


View Tutorial          By: dole at 2011-11-12 06:44:42
62. View Comment

hi ,
i am a beginner in java. please tell me what is the purpose of using "integer " in the statement below
sum += ((Integer) ia[i]).intValue();


View Tutorial          By: aun at 2011-11-18 06:47:56
63. View Comment

Thanx a Lot .Your Soln provided a great help

View Tutorial          By: Amit at 2011-11-21 18:35:56
64. View Comment

Good job. Very clear and concise and a great help...thank you!

View Tutorial          By: Eduardo at 2012-02-08 19:18:50
65. View Comment

The tutorial, it's very easy to be understood
Thank you.


View Tutorial          By: newcomer at 2012-04-25 03:49:35
66. View Comment

Thank you so much. You made my day. God bless you and all

View Tutorial          By: Gautam at 2012-09-18 16:24:19
67. View Comment

Fantastic yaar .realy very good n simple example....Thanks a lot..

View Tutorial          By: Satya at 2012-10-11 09:33:17
68. View Comment

Very good for the example......

View Tutorial          By: Tuhin Subhra Mandal at 2012-10-14 12:22:01
69. View Comment

Thank you, this tutorial is well-written and made me fully understand ArrayList. :D

View Tutorial          By: Adrien Tétar at 2012-10-28 19:01:57
70. View Comment

very nice..thank you so much.all the concepts are explained clearly.

View Tutorial          By: Priya at 2013-01-01 07:39:04
71. View Comment

Thank you so much....
I am going to have java exam tomorrow and you help me so much...thank you....


View Tutorial          By: Mehrnoosh at 2013-06-09 16:50:23
72. View Comment

Very good explanation . i understood easily

View Tutorial          By: whyte at 2014-03-25 10:12:00
73. View Comment

Thanks for your tutorial.

View Tutorial          By: pre pais at 2015-01-09 00:14:29
74. View Comment

its really helpful.thanks a lot

View Tutorial          By: bena at 2015-03-04 10:39:46

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by Hong
How to use ArrayList in Java
Using totalMemory( ) and freeMemory( ) in Java
indexOf( ) and lastIndexOf( ) in Java
Extract characters in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
wait(), notify() and notifyAll() in Java - A tutorial
Read from a COM port using Java program
Recursion in java
FileReader and FileWriter example program in Java
How to use Iterator in Java
Vector example in Java
Using StringTokenizer in Java
XML and Java - Parsing XML using Java Tutorial
Count number of vowels, consonants and digits in a String in Java
Method Overloading (function overloading) in Java
append() in Java
Integer: byte, short, int, and long data types in Java
Garbage collection and Finalize() method
Student marks calculation program in Java
Most Emailed Articles (in Java)
What is Multithreaded programming?
for loop in java
Read from a COM port using Java program
Calculate gross salary in Java
TCP Server and TCP Client in Java
setPriority() and getPriority() in Java
constants and variables
Calculate average sale of the week in Java
wait(), notify() and notifyAll() in Java - A tutorial
? - ternary (three-way) operator - in Java
Window Object
Why java is important to the Internet
Update contents of a file within a jar file
Handling Fractions in Java
HTTPS Java - URL Connection program. Using HttpsURLConnection