How to get sublist of an ArrayList with example?
The subList method returns a list therefore to store the sublist in another ArrayList we must need to type cast the returned value in same way as I did in the below example. On the other side if we are storing the returned sublist into a list then there is no need to type cast.
package com.mindclues; import java.util.ArrayList; import java.util.List; public class ArrayListExample { public static void main(String a[]){ ArrayListal = new ArrayList (); //Addition of elements in ArrayList al.add("A"); al.add("B"); al.add("C"); al.add("D"); al.add("E"); al.add("F"); System.out.println(" ArrayList Content: "+al); //Sublist to ArrayList ArrayList al2 = new ArrayList (al.subList(1, 4)); System.out.println("SubList elements in ArrayList: "+al2); //Sublist to List List list = al.subList(1, 4); System.out.println("SubList elements in List: "+list); } }
ArrayList Content: [A, B, C, D, E, F] SubList elements in ArrayList: [B, C, D] SubList elements in List: [B, C, D]
post a comment