To get the size of ArrayList we can use the library method size() ,but here requirement is not to use the size() method. so that we can use Iterator to get the size of ArrayList. the logic to get the size of ArrayList is simple.
- First add the element in ArrayList using add() method.
- Now take an Iterator to iterate the ArrayList one by one.the code to do that is following..
Iterator
itr=al.iterator();
while(itr.hasNext())
{
itr.next();
count++;
}
|
3. By increasing the count we can get the size of ArrayList. because when itr.next() will call it will access the element one by one and at that time
count will also increase.
4. finally we will get the size of ArrayList.
The code is following to do that-
import
java.util.ArrayList;
import java.util.Iterator;
class ArrayListSize
{
public static void
main(String[] args)
{
int
count=0;
ArrayList
al=new ArrayList<>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
al.add(50);
System.out.println("Size of ArrayList ::"+al.size());
Iterator
itr=al.iterator();
while(itr.hasNext())
{
itr.next();
count++;
}
System.out.println("Size of ArrayList ::"+count);
}
}
Output: