- Automatic-resizable array and used in place of array
- Once size is set can’t be modified
- Implement List and allow null
- Maintains Insertion order
- Allows duplicates
- ListIterator and Iterator both can be used. Prefer
listiterator since it can traverse in both direction and modify the list
as well
- ArrayList is not synchronized so should not be shared
between multiple threads.
a.
If multiple threads
access concurrently, and one thread modifies the list it MUST be synchronized
externally
b.
Else it should be
wrapped using Collections.synchronizedList() method. Should be synchronized at
the creation time to avoid any unsynchronized access
c.
Using
CopyOnWriteArrayList which is creates a fresh copy of underlying array for all
operations like add, remove etc,
- Creating ArrayList
ArrayList<String>
arrayList=new
ArrayList<>();
ArrayList<String> arrayList1=new ArrayList<String>();
- Adding Elements
arrayList.add(new Integer(1)); -- Compilation
Error
arrayList.add("A");
arrayList.add("B");
arrayList.add("A");
Output: [A,B,A]
- Size: size() Arraylist size could be different from the
backing array size
- indexOf(obj): returns the first index of object if
found else -1. Internally uses .equals() method to find object so either
implement hashcode() and .equals() method or Object class’s by default
will be used.
- boolean contains() : search an object in arraylist or
we can use Collections.binarySearch().
- isEmpty(): to check if it is empty
- remove(): can remove by passing the object or index.
Else through iterator also we can remove.
Iterator iterator=arrayList.iterator();
while (iterator.hasNext()) {
String
str=iterator.next().toString();
if(str.equals("B")){
arrayList.remove(1);-- ConcurrentModificationException
iterator.remove(); -- B
will be removed
}
}
- boolean addAll(ArrayList): if we want to add copy of
existing list or add a list to already existing
ArrayList<String> copyList1=new ArrayList<>();
copyList1.addAll(arrayList); -- true
System.out.println(copyList1); -- [arraylist…]
ArrayList<String>
addList1=new
ArrayList<>();
addList1.add("D");
addList1.addAll(arrayList); -- true
System.out.println(addList1);--
[D,arraylist …]
- set(int Index, element): replace
- clear() : remove all elements from arraylist. It can be
used again.
- Converting arraylist to array
a. Array list can hold both primitives and objects
while arrayList can hold only objects
b. List<String> arrayList=Arrays.asList(String[])
c. List<String> arrayList= new ArrayList();
String[] A={“A”,”B”};
String[] A={“A”,”B”};
Collections.addAll(arrayList,
A);
- mk
Array v/s ArrayList
- ArrayList is a class and has methods. Array is an object so no methods we can get only length