In: Computer Science
Provide two page paper describing about Array list and operations & Iterators with very suitable examples.
ArrayList is based on Array data structure and implementes List interface. ArrayList is a resizable-array.
Array has fixed length. If the array is full you can't add more elements in it. To overcome this problem, arrayList is used. It can dynamically grow with no size limit. So it is called resizable array.
syntax of class ArrayList :
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
You can defined arrayList as :
ArrayList<Integer> arrList = new
ArrayList<Integer>();
It will create a empty arrayList named arrList.
Basic operations on arrayList :
For e.g.
arrList.add(5)
arrList.add(10)
It will add 5 and 10 in the arrList
Thus, when you print arrList it will give output as [5, 10]
For e.g.
arrList.remove(1)
At index 1, we have 10. So it will be removed.
Thus, when you print arrList it will give output as [5]
For e.g.
arrList.isEmpty()
It will return false as we have one element in the arrList.
For e.g.
arrList.get(0)
It will return 5, as at index 0, we have 5
For e.g.
arrList.indexOf(5)
It will return 0, as at index 0, we have 5
For e.g.
arrList.clear()
Now, arrList becomes null
For e.g.
arrList.set(0,10)
It will add 10 at 0th position.
For e.g.
arrList.size()
It will return 1 as we have only one element in arrList
Iterators :
To iterate a arrayList, we have iterator() method
Iterator iterator()
No any parameters are needed in this method. It returns an
iterator over the elements presents in the list.
See given code snippet :
ArrayList<String>arrlist = new ArrayList<String>(); //It will create arrayList of string type
//adds an elements in the list
arrlist.add("abc");
arrlist.add("def");
arrlist.add("ghi");
arrlist.add("jkl");
System.out.println(arrlist); // [abc, def, ghi, jkl]
//To initialize iterator of string type on arrlist
Iterator<String> iterator = arrlist.iterator();
while (iterator.hasNext())
{
String i = iterator.next();
System.out.println(i);
}
In each iteration, it will print one element of an arrlist
In above example,
hasNext() method is used to loop through whole arrlist
next() will return the next element
You can also use for loop to iterate an arrayList same as below
for (int i : arrlist) {
System.out.println(i);
}