/** Author : Michael Robinson Program : arrayList_Iterators.java Purpose : How to create a Java ArrayList using Iterators. Shows how to add elements to an ArrayList How to delete items How to get and print data items using for loops. Updated : July 2nd, 2012 */ import java.util.ArrayList; import java.util.Iterator; public class arrayList_Iterators { public static void alphaArrayList() { System.out.println("------------------------------------------"); System.out.println(" Processing ArrayList of String data type"); System.out.println(" using ITERATORS "); System.out.println("------------------------------------------"); System.out.println(" Creating ArrayList..."); //create an ArrayList object ArrayList arrayList = new ArrayList(); System.out.println(" Adding data elements to the ArrayList..."); //Add elements to Arraylist using arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.add("d"); arrayList.add("e"); arrayList.add("f"); System.out.println("\n Getting data elements from the ArrayList"); System.out.println(" Iterating through ArrayList elements..."); //This is a loop type class which allows to loop thru the ArrayList Iterator itr = arrayList.iterator(); //use hasNext() and next() methods of Iterator to iterate through the ArrayLis while(itr.hasNext()) { System.out.print(" "+itr.next()); } //now remove elements !!! always remove from the highest to the lowest location System.out.println("\n\n Removing data elements from the ArrayList on index 3 = " + arrayList.get(3) + "\n and index 1 = " + arrayList.get(1) ); arrayList.remove(3); arrayList.remove(1); System.out.println(); System.out.println(" Getting data elements from the ArrayList after removing"); System.out.println(" Iterating through ArrayList elements..."); itr = arrayList.iterator(); //reset iterator to beginning of ArrayList //use hasNext() and next() methods of Iterator to iterate through the ArrayLis while(itr.hasNext()) { System.out.print(" "+itr.next()); } System.out.println("\n\n"); }//end public static void alphaArrayList() public static void numericArrayList() { System.out.println("------------------------------------------"); System.out.println(" Processing ArrayList of Integer data type"); System.out.println(" using ITERATORS "); System.out.println("------------------------------------------"); System.out.println(" Creating ArrayList..."); //create an ArrayList object ArrayList arrayList = new ArrayList(); System.out.println(" Adding data elements to the ArrayList..."); //Add elements to Arraylist using arrayList.add(1100); arrayList.add(2100); arrayList.add(3100); arrayList.add(4100); arrayList.add(5100); arrayList.add(6100); System.out.println("\n Getting data elements in the ArrayList"); System.out.println(" Iterating through ArrayList elements..."); //This is a loop type class which allows to loop thru the ArrayList Iterator itr = arrayList.iterator(); //use hasNext() and next() methods of Iterator to iterate through the ArrayLis while(itr.hasNext()) { System.out.print(" "+itr.next()); } System.out.println("\n\n Removing data elements from the ArrayList on index 3 = " + arrayList.get(3) + "\n and index 1 = " + arrayList.get(1) ); //now remove some !!! always remove from the height to the lowest arrayList.remove(3); arrayList.remove(1); System.out.println("\n Getting data elements from the ArrayList after removing"); System.out.println(" Iterating through ArrayList elements..."); itr = arrayList.iterator(); //reset iterator to beginning of ArrayList //use hasNext() and next() methods of Iterator to iterate through the ArrayLis while(itr.hasNext()) { System.out.print(" "+itr.next()); } }//end public static void numericArrayList() public static void main(String[] args) { alphaArrayList(); numericArrayList(); } } /* ArrayList in Java is most frequently used collection class after HashMap in Java. Java ArrayList represents an automatic resizable array and used in place of array. Since we can not modify size of an array after creating it, we prefer to use ArrayList in Java which re-size itself automatically once it gets full. ArrayList in Java implements List interface and allow null. Java ArrayList also maintains insertion order of elements and allows duplicates opposite to any Set implementation which doesn't allow duplicates. ArrayList supports both Iterator and ListIterator for iteration but it’s recommended to use ListIterator as it allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. But while using ListIterator you need to be little careful because ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous () and the element that would be returned by a call to next (). In this Java ArrayList tutorial we will see how to create Java ArrayList and perform various operations on Java ArrayList. It’s also important to remember that ArrayList is not synchronized and should not be shared between multiple threads. If multiple threads access a Java ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (As per Java doc a structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. It’s recommended to synchronize the list at the creation time to avoid any accidental unsynchronized access to the list. Another better option is to use CopyOnWriteArrayList which is added from Java 5 and optimized for multiple concurrent read. In CopyOnWriteArrayList all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array and that's why it is called as "CopyOnWrite" //Size of an ArrayList in Java is total number of elements currently stored in ArrayList. int size = stringList.size(); //You can use indexOf() method of ArrayList in Java to find out index of a particular object. int index = stringList.indexOf("Item"); for (int i = 0; i String item = stringList.get(i); } //From Java 5 onwards you can use foreach loop as well for(String item: stringList){ System.out.println("retreived element: " + item); } //Checking ArrayList for an Item //Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use contains () method of Java. contains() method takes type of object defined in ArrayList creation and returns true if this list contains the specified element. boolean result = stringList.isEmpty(); stringList.remove(0); stringList.remove(item); //Copying data from one ArrayList to another ArrayList in Java ArrayList copyOfStringList = new ArrayList(); copyOfStringList.addAll(stringList); //Replacing an element at a particular index //You can use set (int index, E element) method of java ArrayList to replace any element from a particular index. Below code will replace first element of stringList from "Item" to "Item2". stringList.set(0,"Item2"); //Clearing all data from ArrayList //ArrayList in Java provides clear () method which removes all of the elements from this list. and make the list empty. You can reuse Java ArrayList after clearing it. stingList.clear(); //Converting from ArrayList to Array in Java //Java ArrayList provides you facility to get the array back from your ArrayList. You can use toArray(T[] a) method returns an array containing all of the elements in this list in proper sequence (from first to last element). "a" is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose. String[] itemArray = new String[stringList.size()]; String[] returnedArray = stringList.toArray(itemArray); Creating Synchronized ArrayList Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use Collections utility class for this purpose as shown below. List list = Collections.synchronizedList(new ArrayList(...)); 14) Creating ArrayList from Array in Java ArrayList in Java is amazing you can create even an ArrayList full of your element from an already existing array. You need to use Arrays.asList(T... a) method for this purpose which returns a fixed-size list backed by the specified array. ArrayList stringList = Arrays.asList(new String[]{"One", "Two", "Three"); 15) Traversing in ArrayList in Java You can use either Iterator or ListIterator for traversing on Java ArrayList. ListIterator will allow you to traverse in both directions while both Iterator and ListIterator will allow you to remove elements from ArrayList in Java while traversing. Iterator itr = stringList.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } ListIterator listItr = stringList.listIterator(); while(listItr.hasNext()){ System.out.println(itr.next()); } 16) Sorting elements of ArrayList in Java You can use Collections.sort(List list) method to sort a Java ArrayList in natural order defined by Comparable interface and can use Collections.sort(List list, Comparator c) method to sort your Java ArrayList based upon provided Comparator. 1) ArrayList is not a synchronized collection hence it is not suitable to be used between multiple threads concurrently. If you want to use ArrayList then you need to either use new CopyonWriteArrayList or use Collections.synchronizedList() to create a synchronized List. 2) CopyonWriteArrayList is recommended for concurrent multi-threading environment as it is optimized for multiple concurrent read and creates copy for write operation. 3) When ArrayList gets full it creates another array and uses System.arrayCopy() to copy all elements from one array to another array. 4) Iterator and ListIterator of java ArrayList are fail-fast it means if Arraylist is structurally modified at any time after the Iterator is created, in any way except through the iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, that's why it’s called fail-fast. 5) ConcurrentModificationException is not guaranteed and it only thrown at best effort. 6) If you are creating Synchronized List it’s recommended to create while creating instance of underlying ArrayList to prevent accidental unsynchronized access to the list. 7) An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation due to incremental filling of ArrayList. 8) The size, isEmpty, get, set, Iterator, and ListIterator operations run in constant time because ArrayList is based on Array but adding or removing an element is costly as compared to LinkedList. 9) ArrayList class is enhanced in Java5 to support Generics which added extra type-safety on ArrayList. It’s recommended to use generics version of ArrayList to ensure that your ArrayList contains only specified type of element and avoid any ClassCastException. 10) Since ArrayList implements List interface it maintains insertion order of element and allow duplicates. 11)If we set Arraylist reference null in Java all the elements inside Arraylist becomes eligible to garbage collection in java , provided there are no more reference exists for those objects. ======================================= /* Java ArrayList example. This Java ArrayList example describes the basic operations performed on the ArrayList. */ /* import java.util.ArrayList; import java.util.Iterator; public class ArrayListExample{ public static void main(String args[]){ // constructs a new empty ArrayList ArrayList arrayList = new ArrayList(); /* To specify initial capacity, use following constructor. ArrayList ArrayList = new ArrayList(100); To create ArrayList from Collection use following constructor ArrayList ArrayList = new ArrayList(Collection collection); In this case the initial capacity would be 110% of the size of the collection. */ /* To add value into ArrayList use add() method. Signature of the add() method is, boolean add(Object object) The value would be appended to the list. To insert value into ArrayList at particular index, use void add(int index, Object object) This method will shifts the subsequent elements of the list. To append all elements of the collection to existing list, use boolean addAll(Collection c) To insert all elements of the collection into existing list, use boolean addAll(int index, Collection collection) To replace particular element in the ArrayList, use Object set(int index, Object value) It returns the previous element present at the specified index. */ /* arrayList.add(new Integer(1)); //adding value to ArrayList arrayList.add(new Integer(2)); arrayList.add(new Integer(3)); /* IMPORTANT : We CAN NOT add primitives to the ArrayList. We have to wrap it into one of the wrapper classes before adding. */ //get number of keys present in the ArrayList /* System.out.println("ArrayList contains " + arrayList.size() + " elements."); /* To check whether ArrayList is empty or not, use isEmpty() method. isEmpty() returns true is ArrayList is empty, otherwise false. Finding particular value from the ArrayList: ArrayList's contains() method returns boolean depending upon the presence of the value in given ArrayList. Signature of the containsValue method is, boolean contains(Object value) */ /* if( arrayList.contains( new Integer(1) ) ){ System.out.println("ArrayList contains 1 as value"); }else{ System.out.println("ArrayList does not contain 1 as value"); } /* Use get method of ArrayList to get value. Signature of the get method is, Object get(int index) */ /* Integer one = (Integer) arrayList.get(0); System.out.println("Value at 0 index is " + one); /* IMPORTANT: get method returns Object, so we need to downcast it. */ /* To search element within the ArrayList, use int indexOf(Object element) it returns the index of first occurrence of the specified element. To find last occurrence of the specified element, use int lastIndexOf(Object element) */ /* System.out.println("Index of first occurrence of 1 is " + arrayList.indexOf(new Integer(1))); /* To convert ArrayList to object array, use Object[] toArray() method. This method returns an Object array containing all elements of the ArrayList in the correct order. */ /* System.out.println("Converting ArrayList to Object array"); Object[] elements = arrayList.toArray(); for(int i=0; i < elements.length ; i++) System.out.println(elements[i]); /* To remove particular element from the ArrayList use, Object remove(int index) It returns the element that was removed from the list. To remove multiple elements from the ArrayList use, void removeRange(int fromIndex, int toIndex). It removes elements from the list whose index is between startIndex (inclusive) and toIndex(Exclusive). To remove all elements of the ArrayList use, void clear(). It removes all elements of the ArrayList. */ /* System.out.println("Is 1 removed from the ArrayList ? " + arrayList.remove(new Integer(1))); } } /* OUTPUT of the above given Java ArrayList Example would be: ArrayList contains 3 key value pair. ArrayList contains 1 as value Value at 0 index is 1 Index of first occurrence of 1 is 0 Converting ArrayList to Object array 1 2 3 Is 1 removed from the ArrayList ? true */