How to use ArrayList in Java
By Hong Viewed: 33766 times Emailed: 342 times Printed: 608 times
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 |
| 2. | Great guide. Missed the lecture, and this summed everything up in a quick and to the point manner. |
| 3. | great! |
| 4. | I love http://www.java-samples.com very much , I was given and provided a very great and valuable knowledge |
| 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..... |
| 6. | very simple explanation...... |
| 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? |
| 8. | Hi Jon, |
| 9. | Great tutorial about ArrayList .It's a very great and valuable knowledge for me. |
| 10. | Just what I needed. Thank you. |
| 11. | My friend, How to user ArrayList? |
| 12. | can i apply multidimensional array list the program!! |
| 13. | what's the deffrint between "String[] [] ArrayList" |
| 14. | good work done. |
| 15. | It's really helpful , thanks a lot |
| 16. | What kind of elements can be stored in arraylist ? |
| 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! |
| 18. | Cool it help me a lot |
| 19. | Thanx u m at lab..n u made me complete my prog! |
| 20. | wonderful |
| 21. | Nice code easily understand the code and useful |
| 22. | how do i cast the contents of the arraylist to double??? |
| 23. | It was actually useful!!! Thanks for explaining in 5 min what my professor failed to explain in an hour's lecture. |
| 24. | Good work, IT really help me a lot; |
| 25. | I entered four different objects into an ArrayList using the add function. |
| 26. | Nice Work... Keep it.. |
| 27. | good but not best |
| 28. | very simple explanation |
| 29. | Wow thx, this is really easy for me to understand |
| 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. |
| 31. | hey.. |
| 32. | i need save,delete,update use arrayList. |
| 33. | "Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList |
| 34. | It was sooo helpful for me |
| 35. | Really superb.Simple code.Thanks. |
| 36. | Good explaination, easy to understand |
| 37. | M having query |
| 38. | My Friend, |
| 39. | Wow Its awesome. |
| 40. | this is good arraylist |
| 41. | thanku verymuch. very helpfull |
| 42. | Very well Explained Thank you Hog . |
| 43. | i like this site.good explanation,but it is good for beginners. |
| 44. | good going java samples |
| 45. | well written hog .good going |
| 46. | it is gooo...very helpful to know the basics |
Latest Tutorials
More Latest News
Most Viewed Articles (in last 30 days)

