Thursday, February 12, 2009

Java Collections And Data Structures ( java.util package ) » ArrayList

Home » Java Collections And Data Structures ( java.util package ) » ArrayList


ArrayList
Java ArrayList is a resizable array which implements List interface. ArrayList provides all operation defined by List interface. Internally ArrayList uses an array to store its elements. ArrayList provides additional methods to manipulate the array that actually stores the elements.
ArrayList is equivalent to Vector, but ArrayList is not synchronized.
Java ArrayList Capacity
Capacity of an ArrayList is the size of the array used to store the list elements. It grows automatically as we add elements to it. Every time this happens, the internal array has to be reallocated. This increases the load.
We can set the initial capacity of the ArrayList using following method.
ArrayList arrayList = new ArrayList();
arrayList.ensureCapacity(100);
Java ArrayList Iterators
Java ArrayList provides two types of Iterators.
1) Iterator
2) ListIterator
Iterator iterator = arrayList.iterator();
Returns object of Iterator.
ListIterator listIterator = arrayList.listIterator();
Returns object of ListIterator.
ListIterator listIterator = arrayList.listIterator(int startIndex);
Returns object of ListIterator. The first next() method call on this ListIterator object will return the element at the specified index passed to get the ListIterator object.
Iterators returned by these methods are fail-fast. That means if the list is modified after getting the Iterator by using some other means rather than Iterators own add or remove method, Iterator will throw ConcurrentModificationException.


ArrayList Constructors
1) ArrayList()
Creates an empty ArrayList.
For example,
ArrayList arrayList = new ArrayList();
2) ArrayList(int capacity)
Creates an ArrayList with specified initial capacity.
For example,
ArrayList arrayList = new ArrayList(10);
3) ArrayList(Collection c)
Creates an ArrayList containing elements of the collection specified.
For example,
ArrayList arrayList = new ArrayList(myCollection);
Where myCollection is an object of the type Collection. This creates an ArrayList of elements contained in the myCollection, in the order returned by the myCollection’s Iterator.
Java ArrayList Examples
• Add an element to specified index of Java ArrayList Example
• Append all elements of other Collection to Java ArrayList Example
• Copy all elements of Java ArrayList to an Object Array Example
• Get Size of Java ArrayList and loop through elements Example
• Get Sub List of Java ArrayList Example
• Insert all elements of other Collection to Specified Index of Java ArrayList Example
• Iterate through elements Java ArrayList using Iterator Example
• Iterate through elements Java ArrayList using ListIterator Example
• Remove all elements from Java ArrayList Example
• Remove an element from specified index of Java ArrayList Example
• Replace an element at specified index of Java ArrayList Example
• Search an element of Java ArrayList Example
• Simple Java ArrayList Example
• Sort elements of Java ArrayList Example





Add an element to specified index of Java ArrayList Example
1. /*
2. Add an element to specified index of Java ArrayList Example
3. This Java Example shows how to add an element at specified index of java
4. ArrayList object using add method.
5. */
6.
7. import java.util.ArrayList;
8.
9. public class AddElementToSpecifiedIndexArrayListExample {
10.
11. public static void main(String[] args) {
12. //create an ArrayList object
13. ArrayList arrayList = new ArrayList();
14.
15. //Add elements to Arraylist
16. arrayList.add("1");
17. arrayList.add("2");
18. arrayList.add("3");
19.
20. /*
21. To add an element at the specified index of ArrayList use
22. void add(int index, Object obj) method.
23. This method inserts the specified element at the specified index in
24. the ArrayList.
25. */
26. arrayList.add(1,"INSERTED ELEMENT");
27.
28. /*
29. Please note that add method DOES NOT overwrites the element previously
30. at the specified index in the list. It shifts the elements to right
31. side and increasing the list size by 1.
32. */
33.
34. System.out.println("ArrayList contains...");
35. //display elements of ArrayList
36. for(int index=0; index < arrayList.size(); index++)
37. System.out.println(arrayList.get(index));
38.
39. }
40. }
41.
42. /*
43. Output would be
44. ArrayList contains...
45. 1
46. INSERTED ELEMENT
47. 2
48. 3
49. */

Append all elements of other Collection to Java ArrayList Example
1. /*
2. Append all elements of other Collection to Java ArrayList Example
3. This Java Example shows how to append all elements of other Collection object
4. at the end of Java ArrayList object using addAll method. This program shows
5. how to append all elements of Java Vector to Java ArrayList object.
6. */
7.
8. import java.util.ArrayList;
9. import java.util.Vector;
10.
11. public class AppendAllElementsOfOtherCollectionToArrayListExample {
12.
13. public static void main(String[] args) {
14.
15. //create an ArrayList object
16. ArrayList arrayList = new ArrayList();
17.
18. //Add elements to Arraylist
19. arrayList.add("1");
20. arrayList.add("2");
21. arrayList.add("3");
22.
23. //create a new Vector object
24. Vector v = new Vector();
25. v.add("4");
26. v.add("5");
27.
28. /*
29. To append all elements of another Collection to ArrayList use
30. boolean addAll(Collection c) method.
31. It returns true if the ArrayList was changed by the method call.
32. */
33.
34. //append all elements of Vector to ArrayList
35. arrayList.addAll(v);
36.
37. //display elements of ArrayList
38. System.out.println("After appending all elements of Vector,
39. ArrayList contains..");
40. for(int i=0; i41. System.out.println(arrayList.get(i));
42.
43. }
44. }
45.
46. /*
47. Output would be
48. After appending all elements of Vector, ArrayList contains..
49. 1
50. 2
51. 3
52. 4
53. 5
54. */
Copy all elements of Java ArrayList to an Object Array Example
1. /*
2. Copy all elements of Java ArrayList to an Object Array Example
3. This Java Example shows how to copy all elements of Java ArrayList object to an
4. array of Objects using toArray method.
5. */
6.
7. import java.util.ArrayList;
8.
9. public class CopyElementsOfArrayListToArrayExample {
10.
11. public static void main(String[] args) {
12. //create an ArrayList object
13. ArrayList arrayList = new ArrayList();
14.
15. //Add elements to ArrayList
16. arrayList.add("1");
17. arrayList.add("2");
18. arrayList.add("3");
19. arrayList.add("4");
20. arrayList.add("5");
21.
22. /*
23. To copy all elements of java ArrayList object into array use
24. Object[] toArray() method.
25. */
26.
27. Object[] objArray = arrayList.toArray();
28.
29. //display contents of Object array
30. System.out.println("ArrayList elements are copied into an Array.
31. Now Array Contains..");
32. for(int index=0; index < objArray.length ; index++)
33. System.out.println(objArray[index]);
34. }
35. }
36.
37. /*
38. Output would be
39. ArrayList elements are copied into an Array. Now Array Contains..
40. 1
41. 2
42. 3
43. 4
44. 5
45. */




Get Size of Java ArrayList and loop through elements Example
1. /*
2. Get Size of Java ArrayList and loop through elements Example
3. This Java Example shows how to get size or number of elements currently
4. stored in ArrayList. It also shows how to loop through element of it.
5. */
6.
7. import java.util.ArrayList;
8.
9. public class GetSizeOfArrayListExample {
10.
11. public static void main(String[] args) {
12. //create an ArrayList object
13. ArrayList arrayList = new ArrayList();
14.
15. //Add elements to Arraylist using
16. arrayList.add("1");
17. arrayList.add("2");
18. arrayList.add("3");
19.
20. //To get size of Java ArrayList use int size() method
21. int totalElements = arrayList.size();
22.
23. System.out.println("ArrayList contains...");
24. //loop through it
25. for(int index=0; index < totalElements; index++)
26. System.out.println(arrayList.get(index));
27.
28. }
29. }
30.
31. /*
32. Output would be
33. ArrayList contains...
34. 1
35. 2
36. 3
37. */
Get Sub List of Java ArrayList Example
1. /*
2. Get Sub List of Java ArrayList Example
3. This Java Example shows how to get sub list of java ArrayList using subList
4. method by providing start and end index.
5. */
6.
7. import java.util.ArrayList;
8. import java.util.List;
9.
10. public class GetSubListOfJavaArrayListExample {
11.
12. public static void main(String[] args) {
13.
14. //create an ArrayList object
15. ArrayList arrayList = new ArrayList();
16.
17. //Add elements to Arraylist
18. arrayList.add("1");
19. arrayList.add("2");
20. arrayList.add("3");
21. arrayList.add("4");
22. arrayList.add("5");
23.
24. /*
25. To get a sub list of Java ArrayList use
26. List subList(int startIndex, int endIndex) method.
27. This method returns an object of type List containing elements from
28. startIndex to endIndex - 1.
29. */
30.
31. List lst = arrayList.subList(1,3);
32.
33. //display elements of sub list.
34. System.out.println("Sub list contains : ");
35. for(int i=0; i< lst.size() ; i++)
36. System.out.println(lst.get(i));
37.
38. /*
39. Sub List returned by subList method is backed by original Arraylist.
40. So any changes made to sub list will also be REFLECTED in the original
41. Arraylist.
42. */
43. //remove one element from sub list
44. Object obj = lst.remove(0);
45. System.out.println(obj + " is removed from sub list");
46.
47. //print original ArrayList
48. System.out.println("After removing " + obj + " from sub list, original
49. ArrayList contains : ");
50. for(int i=0; i< arrayList.size() ; i++)
51. System.out.println(arrayList.get(i));
52.
53. }
54.
55. }
56. /*
57. Output would be
58. Sub list contains :
59. 2
60. 3
61. 2 is removed from sub list
62. After removing 2 from sub list original ArrayList contains :
63. 1
64. 3
65. 4
66. 5
67. */
Insert all elements of other Collection to Specified Index of Java ArrayList Example
1. /*
2. Insert all elements of other Collection to Specified Index of Java
3. ArrayList Example
4. This Java Example shows how to insert all elements of other Collection object
5. at specified index of Java ArrayList object using addAll method.
6. */
7.
8. import java.util.ArrayList;
9. import java.util.Vector;
10.
11. public class InsertAllElementsOfOtherCollectionToArrayListExample {
12.
13. public static void main(String[] args) {
14.
15. //create an ArrayList object
16. ArrayList arrayList = new ArrayList();
17.
18. //Add elements to Arraylist
19. arrayList.add("1");
20. arrayList.add("2");
21. arrayList.add("3");
22.
23. //create a new Vector object
24. Vector v = new Vector();
25. v.add("4");
26. v.add("5");
27.
28. /*
29. To insert all elements of another Collection to sepcified index of
30. ArrayList use boolean addAll(int index, Collection c) method.
31. It returns true if the ArrayList was changed by the method call.
32. */
33.
34. //insert all elements of Vector to ArrayList at index 1
35. arrayList.addAll(1,v);
36.
37. //display elements of ArrayList
38. System.out.println("After inserting all elements of Vector at index 1,
39. ArrayList contains..");
40. for(int i=0; i41. System.out.println(arrayList.get(i));
42.
43. }
44. }
45.
46. /*
47. Output would be
48. After inserting all elements of Vector at index 1, ArrayList contains..
49. 1
50. 4
51. 5
52. 2
53. 3
54. */
Iterate through elements Java ArrayList using Iterator Example
1. /*
2. Iterate through elements Java ArrayList using Iterator Example
3. This Java Example shows how to iterate through the elements of java
4. ArrayList object using Iterator.
5. */
6.
7. import java.util.ArrayList;
8. import java.util.Iterator;
9.
10. public class IterateThroughArrayListUsingIteratorExample {
11.
12. public static void main(String[] args) {
13.
14. //create an ArrayList object
15. ArrayList arrayList = new ArrayList();
16.
17. //Add elements to Arraylist
18. arrayList.add("1");
19. arrayList.add("2");
20. arrayList.add("3");
21. arrayList.add("4");
22. arrayList.add("5");
23.
24. //get an Iterator object for ArrayList using iterator() method.
25. Iterator itr = arrayList.iterator();
26.
27. //use hasNext() and next() methods of Iterator to iterate through the
28. //elements
29. System.out.println("Iterating through ArrayList elements...");
30. while(itr.hasNext())
31. System.out.println(itr.next());
32.
33. }
34. }
35.
36. /*
37. Output would be
38. Iterating through ArrayList elements...
39. 1
40. 2
41. 3
42. 4
43. 5
44. */

Iterate through elements Java ArrayList using ListIterator Example
1. /*
2. Iterate through elements Java ArrayList using ListIterator Example
3. This Java Example shows how to iterate through the elements of java
4. ArrayList object in forward and backward direction using ListIterator.
5. */
6.
7. import java.util.ArrayList;
8. import java.util.ListIterator;
9.
10. public class IterateThroughArrayListUsingListIteratorExample {
11.
12. public static void main(String[] args) {
13.
14. //create an ArrayList object
15. ArrayList arrayList = new ArrayList();
16.
17. //Add elements to Arraylist
18. arrayList.add("1");
19. arrayList.add("2");
20. arrayList.add("3");
21. arrayList.add("4");
22. arrayList.add("5");
23.
24. /*
25. Get a ListIterator object for ArrayList using
26. listIterator() method.
27. */
28. ListIterator itr = arrayList.listIterator();
29.
30. /*
31. Use hasNext() and next() methods of ListIterator to iterate through
32. the elements in forward direction.
33. */
34. System.out.println("Iterating through ArrayList elements in forward
35. direction...");
36. while(itr.hasNext())
37. System.out.println(itr.next());
38.
39. /*
40. Use hasPrevious() and previous() methods of ListIterator to iterate
41. through the elements in backward direction.
42. */
43. System.out.println("Iterating through ArrayList elements in backward
44. direction...");
45. while(itr.hasPrevious())
46. System.out.println(itr.previous());
47.
48. }
49. }
50.
51. /*
52. Output would be
53. Iterating through ArrayList elements...
54. Iterating through ArrayList elements in forward direction...
55. 1
56. 2
57. 3
58. 4
59. 5
60. Iterating through ArrayList elements in backward direction...
61. 5
62. 4
63. 3
64. 2
65. 1
66. */
Remove all elements from Java ArrayList Example
1. /*
2. Remove all elements from Java ArrayList Example
3. This Java Example shows how to remove all elements from java ArrayList object
4. using clear method.
5. */
6.
7. import java.util.ArrayList;
8.
9. public class RemoveAllElementsOfArrayListExample {
10.
11. public static void main(String[] args) {
12. //create an ArrayList object
13. ArrayList arrayList = new ArrayList();
14.
15. //Add elements to Arraylist
16. arrayList.add("1");
17. arrayList.add("2");
18. arrayList.add("3");
19.
20. System.out.println("Size of ArrayList before removing elements : "
21. + arrayList.size());
22. /*
23. To remove all elements from the ArrayList use
24. void clear() method.
25. */
26. arrayList.clear();
27. System.out.println("Size of ArrayList after removing elements : "
28. + arrayList.size());
29.
30. }
31. }
32. /*
33. Output would be
34. Size of ArrayList before removing elements : 3
35. Size of ArrayList after removing elements : 0
36. */

Remove an element from specified index of Java ArrayList Example
1. /*
2. Remove an element from specified index of Java ArrayList Example
3. This Java Example shows how to remove an element at specified index of java
4. ArrayList object using remove method.
5. */
6.
7. import java.util.ArrayList;
8.
9. public class RemoveElementFromArrayListExample {
10.
11. public static void main(String[] args) {
12. //create an ArrayList object
13. ArrayList arrayList = new ArrayList();
14.
15. //Add elements to Arraylist
16. arrayList.add("1");
17. arrayList.add("2");
18. arrayList.add("3");
19.
20. /*
21. To remove an element from the specified index of ArrayList use
22. Object remove(int index) method.
23. It returns the element that was removed from the ArrayList.
24. */
25. Object obj = arrayList.remove(1);
26. System.out.println(obj + " is removed from ArrayList");
27.
28. System.out.println("ArrayList contains...");
29. //display elements of ArrayList
30. for(int index=0; index < arrayList.size(); index++)
31. System.out.println(arrayList.get(index));
32.
33. }
34. }
35.
36. /*
37. Output would be
38. 2 is removed from ArrayList
39. ArrayList contains...
40. 1
41. 3
42. */
Replace an element at specified index of Java ArrayList Example
1. /*
2. Replace an element at specified index of Java ArrayList Example
3. This Java Example shows how to replace an element at specified index of java
4. ArrayList object using set method.
5. */
6.
7. import java.util.ArrayList;
8.
9. public class ReplaceElementAtSpecifiedIndexArrayListExample {
10.
11. public static void main(String[] args) {
12. //create an ArrayList object
13. ArrayList arrayList = new ArrayList();
14.
15. //Add elements to Arraylist
16. arrayList.add("1");
17. arrayList.add("2");
18. arrayList.add("3");
19.
20. /*
21. To replace an element at the specified index of ArrayList use
22. Object set(int index, Object obj) method.
23. This method replaces the specified element at the specified index in
24. the ArrayList and returns the element previously at the specified position.
25. */
26. arrayList.set(1,"REPLACED ELEMENT");
27.
28. System.out.println("ArrayList contains...");
29. //display elements of ArrayList
30. for(int index=0; index < arrayList.size(); index++)
31. System.out.println(arrayList.get(index));
32.
33. }
34. }
35.
36. /*
37. Output would be
38. ArrayList contains...
39. 1
40. REPLACED ELEMENT
41. 3
42. */
Search an element of Java ArrayList Example
1. /*
2. Search an element of Java ArrayList Example
3. This Java Example shows how to search an element of java
4. ArrayList object using contains, indexOf and lastIndexOf methods.
5. */
6.
7. import java.util.ArrayList;
8.
9. public class SearchAnElementInArrayListExample {
10.
11. public static void main(String[] args) {
12.
13. //create an ArrayList object
14. ArrayList arrayList = new ArrayList();
15.
16. //Add elements to Arraylist
17. arrayList.add("1");
18. arrayList.add("2");
19. arrayList.add("3");
20. arrayList.add("4");
21. arrayList.add("5");
22. arrayList.add("1");
23. arrayList.add("2");
24.
25. /*
26. To check whether the specified element exists in Java ArrayList use
27. boolean contains(Object element) method.
28. It returns true if the ArrayList contains the specified objct, false
29. otherwise.
30. */
31.
32. boolean blnFound = arrayList.contains("2");
33. System.out.println("Does arrayList contain 2 ? " + blnFound);
34.
35. /*
36. To get an index of specified element in ArrayList use
37. int indexOf(Object element) method.
38. This method returns the index of the specified element in ArrayList.
39. It returns -1 if not found.
40. */
41.
42. int index = arrayList.indexOf("4");
43. if(index == -1)
44. System.out.println("ArrayList does not contain 4");
45. else
46. System.out.println("ArrayList contains 4 at index :" + index);
47.
48. /*
49. To get last index of specified element in ArrayList use
50. int lastIndexOf(Object element) method.
51. This method returns index of the last occurrence of the
52. specified element in ArrayList. It returns -1 if not found.
53. */
54.
55. int lastIndex = arrayList.lastIndexOf("1");
56. if(lastIndex == -1)
57. System.out.println("ArrayList does not contain 1");
58. else
59. System.out.println("Last occurrence of 1 in ArrayList is at index :"
60. + lastIndex);
61.
62. }
63. }
64. /*
65. Output would be
66. Does arrayList contain 2 ? true
67. ArrayList contains 4 at index :3
68. Last occurrence of 1 in ArrayList is at index :5
69. */


Simple Java ArrayList Example
1. /*
2. Simple Java ArrayList Example
3. This Java Example shows how to create an object of Java ArrayList. It also
4. shows how to add elements to ArrayList and how get the same from ArrayList.
5. */
6.
7. import java.util.ArrayList;
8.
9. public class SimpleArrayListExample {
10.
11. public static void main(String[] args) {
12.
13. //create an ArrayList object
14. ArrayList arrayList = new ArrayList();
15.
16. /*
17. Add elements to Arraylist using
18. boolean add(Object o) method. It returns true as a general behavior
19. of Collection.add method. The specified object is appended at the end
20. of the ArrayList.
21. */
22. arrayList.add("1");
23. arrayList.add("2");
24. arrayList.add("3");
25.
26. /*
27. Use get method of Java ArrayList class to display elements of
28. ArrayList.Object get(int index) returns and element at the specified
29. index in the ArrayList
30. */
31. System.out.println("Getting elements of ArrayList");
32. System.out.println(arrayList.get(0));
33. System.out.println(arrayList.get(1));
34. System.out.println(arrayList.get(2));
35. }
36. }
37.
38. /*
39. Output would be
40. Getting elements of ArrayList
41. 1
42. 2
43. 3
44. */



Sort elements of Java ArrayList Example
1. /*
2. Sort elements of Java ArrayList Example
3. This Java Example shows how to sort the elements of java ArrayList object using
4. Collections.sort method.
5. */
6.
7. import java.util.ArrayList;
8. import java.util.Collections;
9.
10. public class SortJavaArrayListExample {
11.
12. public static void main(String[] args) {
13.
14. //create an ArrayList object
15. ArrayList arrayList = new ArrayList();
16.
17. //Add elements to Arraylist
18. arrayList.add("1");
19. arrayList.add("3");
20. arrayList.add("5");
21. arrayList.add("2");
22. arrayList.add("4");
23.
24. /*
25. To sort an ArrayList object, use Collection.sort method. This is a
26. static method. It sorts an ArrayList object's elements into ascending order.
27. */
28. Collections.sort(arrayList);
29.
30. //display elements of ArrayList
31. System.out.println("ArrayList elements after sorting in ascending order :
32. ");
33. for(int i=0; i34. System.out.println(arrayList.get(i));
35.
36. }
37. }
38.
39. /*
40. Output would be
41. ArrayList elements after sorting in ascending order :
42. 1
43. 2
44. 3
45. 4
46. 5
47. */

No comments: