ArrayList in Java is most frequently used collection class after HashMap in Java. Java ArrayList represents an automatic re-sizable 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. This collection class is also favorites on many core Java interviews with questions like Difference between ArrayList and Vector or LinkedList vs ArrayList.
ArrayList has been modified in Java5 (Tiger) to support Generics which makes Java ArrayList even more powerful because of enhanced type-safety. Before Java5 since there was no generics no type checking at compile time which means there is chance of storing different type of element in an ArrayList which is meant for something and ultimately results in ClassCastException during runtime. with generics you can create Java ArrayList which accepts only type of object specified during creation time and results in compilation error if someone tries to insert any other object into ArrayList in Java; for example if you create an ArrayList of String object you can not store Integer on it because add() method of ArrayList will check Type before adding object into ArrayList in Java opposite to add() method of Java4 which accepts any object.
Java ArrayList with Generics in JDK 1.5
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 re-sizes 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 non synchronized 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"
Example of ArrayList in Java
stringList.add(new Integer(2)); //compilation error
for (int i = 0; i < stringList.size(); i++)
String item = stringList.get(i);
System.out.println("Item " + i + " : " + item);
}
From Java 5 onwards you can use foreach loop as well
for(String item: stringList){
System.out.println("retrieved element: " + item);
}
if(stringList.size() == 0){
System.out.println("ArrayList is empty");
}
copyOfStringList.addAll(stringList);
String[] returnedArray = stringList.toArray(itemArray);
If you want to convert ArrayList back to Array than see 3 ways to convert array into arraylist in Java
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.
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.
while(itr.hasNext()){
System.out.println(itr.next());
}
ListIterator listItr = stringList.listIterator();
while(listItr.hasNext()){
System.out.println(itr.next());
}
see How to loop ArrayList in Java for more alternative ways of traversing a List
You can use Collections.sort(List
17) ArrayList to HashSet conversion
Most of Collection class provides a constructor which accepts a Collection object as argument. Which can be used to copy all elements of one Collection into another. HashSet also provide such constructors which can be used to copy all object from ArrayList to HashSet. But be careful since HashSet doesn't allow duplicates some of the objects will not be included which result in less number of objects. See How to convert ArrayList to HashSet in Java for step by step example.
Tips on ArrayList in Java
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.
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.
6) If you are creating Synchronized List it’s recommended to create while creating instance of underlying ArrayList to prevent accidental non synchronized access to the list.
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.
Hope this Java ArrayList tutorial will be helpful for beginners in Java.
Related post:
How Garbage Collection works in Java?
Why String is immutable in Java?
Why wait and notify method must be called in synchronized context?
10 practical tips on Java debugging with eclipse
No comments:
Post a Comment