Site icon JavaGoal

How to access ArrayList in java

In recent posts, we have seen how we can add and remove the element from the ArrayList in java.
In this post, we will see how to access ArrayList in java. There are two ways to access ArrayList in java, we can access the elements randomly and sequentially. As we know ArrayList maintains the insertion order by use of index value so we can get element by a particular index.

Here is the table content of the article will we will cover this topic.
1. Using get(int index) Method
2. Using iterator() Method

Using get(int index) Method

We can randomly access the element of ArrayList by use of get(int index) method. This method takes a parameter of int type and returns the element.

public E get(int index)

Where E represents the type of elements in the ArrayList.
index, At which position element is presented.
return type:  Its return type is E, So it returns the element.

package package1;

import java.util.ArrayList;
public class ArrayListExample 
{
	public static void main(String[] args) 
    {
		ArrayList<Integer> listOfNumbers = new ArrayList<Integer>();
		listOfNumbers.add(111);
		listOfNumbers.add(222);
		listOfNumbers.add(333);
		listOfNumbers.add(444);
		listOfNumbers.add(555);
		
		// To get element particular element by index
		System.out.println("Element presented at index value 1: "+listOfNumbers.get(1));
		
		// To get all element from ArrayList
		System.out.println("Getting all elements: ");
		for(int i = 0; i < listOfNumbers.size(); i++)
			System.out.println(listOfNumbers.get(i));
    }
}

Output: Element presented at index value 1: 222
Getting all elements:
111
222
333
444
555

Using iterator() Method

We can access the elements of ArrayList sequentially by the use of iterator. We must import java.util.Iterator package to use this method. By use of iterator we can’t get element randomly.

public Iterator iterator()

This method returns the object of iterator that used to iterate the elements of ArrayList.

package package1;

import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListExample 
{
	public static void main(String[] args) 
    {
		ArrayList<Integer> listOfNumbers = new ArrayList<Integer>();
		listOfNumbers.add(111);
		listOfNumbers.add(222);
		listOfNumbers.add(333);
		listOfNumbers.add(444);
		listOfNumbers.add(555);
		
		// To get all element from ArrayList
		System.out.println("Getting all elements: ");
		Iterator iterator = listOfNumbers.iterator();
		while(iterator.hasNext())
			System.out.println(iterator.next());
    }
}

Output: Getting all elements:
111
222
333
444
555

Exit mobile version