Write a Java program to Retrieve a portion of an ArrayList


The code is demonstrating how to retrieve a portion of an ArrayList using the subList() method, and how changes made to the original ArrayList and the subList are reflected in each other.

It first creates an ArrayList num with ten integers. Then, it retrieves a portion of the list starting at index 2 and ending at index 8 using the subList() method and assigns it to a new List sub_num. It then prints out the subList.

It then modifies the element at index 3 of the original ArrayList num to be 1000 using the set() method. Since the sub_num list is a view of the original list, the change is also reflected in sub_num.

Finally, it modifies the element at index 5 of the sub_num list to be 8000 using the set() method. Since sub_num is a view of the original list, the change is also reflected in num.

Source Code

import java.util.ArrayList;
import java.util.List;
public class Retrieve_Portion
{
    public static void main(String[] args)
    {
		ArrayList<Integer> num = new ArrayList<Integer>();
		num.add(10); 
		num.add(20); 
		num.add(30); 
		num.add(40); 
		num.add(50); 
		num.add(60);
		num.add(70);
		num.add(80);
		num.add(90);
		num.add(100); 
		System.out.println("Given ArrayList : "+num);
 
		//Retrieving a SubList 
		List<Integer> sub_num = num.subList(2, 8); 
		System.out.println("Retrieving a SubList : "+sub_num);
 
		//Modifying the num 
		num.set(3, 1000); 
		System.out.println("Changes will be Reflected in SubList : "+sub_num); 
 
		//Modifying the subList 
		sub_num.set(5, 8000); 
		System.out.println("Changes will be Reflected in ArrayList : "+num); 
    }
}

Output

Given ArrayList : [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Retrieving a SubList : [30, 40, 50, 60, 70, 80]
Changes will be Reflected in SubList : [30, 1000, 50, 60, 70, 80]
Changes will be Reflected in ArrayList : [10, 20, 30, 1000, 50, 60, 70, 8000, 90, 100]

Example Programs