Friday, July 24, 2015

Java - ArrayList constructors and methods example

ArrayList is a dynamic array that implements the List interface that is a sorted collection that the user of this interface has total control over the inserted elements and position by accessing and searching for items in the list.

ArrayList implements all methods List, more than that, the class has its own methods such as manipulating the size of the array used to store the list. This class is equivalent to Vector.
Arraylist uses an array that stores data, this table has a capability that automatically adapts to each time an item is inserted. There is a ensureCapacity method that increases the capacity of ArrayList before adding many elements to ensure the size.

Access to the list is made simultaneously by multiple threads. This can cause problems when it comes to a change, insert, delete because another thread will access and update the size of the list is underway. The solution is synchronization process using the Collections.synchronizedList method.

List list = Collections.synchronizedList(new ArrayList(...));

To browse the list with the iterator class or ListIterator, but if the list has changed: delete, insert ... after creating iterator, it will trigger a ConcurrentModificationException exception. The solution is to create a mutual exclusion with the aim to prevent other threads to access it after creating iterator and during playback.

ArraylList Consturctors

ArrayList three manufacturer:

- ArrayList (): creates an empty list with an initial size of 10.
- ArrayList (<? Extends E> Collection c) Creates a list from a collection of data and returns a NullPointerException if the collection is zero.
- ArrayList (int size) Creates a list by setting the initial size and returns an IllegalArgumentException if size is negative.

ArrayList Methods

1) add(Object o): add element in the end.
list.add("hello");

2) add(int indice, Object o): insert element in the middle
list.add(2, "hi");
It insert the string in the second position of the list.

3) addAll(Collection c): add a collection to the list.
ArrayList toadd = new ArrayList();
l1.add("e1");
l1.add("e2");
l1.add("e3");
list.addAll(toadd);
This operation add a list toadd to the end of the list.

4) addAll(int indice, Collection c): insert a collection c in the middle
list.addAll(3, l1);
this method insert the collection l1 in the fourth position of the list.

5) clear(): remove all elements from the list.

6) contains(Object o): return true if the searched object o is in the list.
boolean b = list.contains(o)

8) ensureCapacity(int capacite): set and ensure the minimum capacity.
list.ensureCapacity(8);
This will ensure at least 8 elements.

9) get(int index): return object at the specific position.
system.out.println(list.get(3));
This will print the object at the third position.

10) indexOf(Object o): search and return the first occurrece of object o.
int k = indexOf("o2");

11) isEmpty(): if the list is empty, this method return true.
boolean empty = list.isEmpty();

12) remove(Object o): remove the first occurrence of object o.
boolean b = list.remove("o3");
This wil return true if the object o3 is found and deleted with success.

13) removeAll(Collection<?> c): remove all elements that belong to collection c.
AarrayList<String> c = new ArrayList<String>();
c.add("o1");
c.add("o2");
c.add("o3");
list.removeAll(c);

14) removeRange( int startIndex, int endIndex): remove elements between startIndex and endIndex.
list.removeRange(4,7);
This method remove elements between 4 and 7.

15) retainsAll(Collection<?> c):  retain only elements that belong to collection c.

16) set(int index, Object o): set object value in a specific index.
list.set(2, "o4");
object in position 2 has been replaced with value "o54.

17) size(): return the arralist size.

18) subList(int startIndex, int endIndex): return a sublist that belong between startIndex and endIndex.

19) toArray(): create an array from ArrayList.
String[] t = list.toArray();
Result array contains all elments of ArrayList. This method is usefull when you use a method that accept only array type argument.

20) trimToSize(): reduce the storage capacity to its miminum.

How to iterate through ArrayList

We can use two methods:

1) for loop

for(int i = 0; i < list.size(); i++)
    system.out.println(list.get(i));
//if we use generic type. In this example an Integer (ArrayList<Integer>)
for(Integer digit: list)
    system.out.println(digit);

2) Iterator+ while loop

Iterator itr = list.iterator();
while(itr.hasNext())
      system.out.println(itr.next());

ArrayList Exemple

import java.util.ArrayList;

public class Test {

 public static void main(String[] args) {
  
  //create ArrayList with generic string type
  ArrayList<String> stringList= new ArrayList<String>();
  //add elements to arraylist
  stringList.add("e1");
  stringList.add("e2");
  stringList.add("e3");
  stringList.add("e4");
  stringList.add("e5");

  //operations example
  System.out.println("e1 exist ? "+stringList.contains("o3"));
  System.out.println("index of "+"o2: "+stringList.indexOf("o2"));
  System.out.println("e5 is deleted: "+stringList.remove("o2"));
  System.out.println("arraylist size: "+stringList.size());
  System.out.println("sublist[0, 2] : "+stringList.subList(0, 2));
  
  //loop arraylist
  for(String s : stringList)
     System.out.println(s);

  stringList.clear();
  System.out.println("is empty ? "+stringList.isEmpty());
 }
}
Output:
e1 exist ? false
index of o2: -1
e5 is deleted: false
arraylist size: 5
sublist[0, 2] : [e1, e2]
e1
e2
e3
e4
e5
is empty ? true

No comments:

Post a Comment