8

Is there a method in Java to get the list of objects from an Arraylist to another ArrayList, by just specifying the start and end index?

2 Answers 2

16

Yes you can use the subList method:

List<...> list2 = list1.subList(startIndex, endIndex);

This returns a view on that part of the original list, it does not copy the data.
If you want a copy:

List<...> list2 = new ArrayList<...> (list1.subList(startIndex, endIndex));
2
  • 1
    That's right, but be aware that the references to the objects stay the same. So if you change your objects in the subList they will also be changed in the first list.
    – Chris
    Aug 9, 2012 at 9:40
  • @Chris yes the second version is not a deep copy, it only copies objects' references.
    – assylias
    Aug 9, 2012 at 9:41
0
/create an ArrayList object
    ArrayList arrayList = new ArrayList();

    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");

    /*
       To get a sub list of Java ArrayList use
       List subList(int startIndex, int endIndex) method.
       This method returns an object of type List containing elements from
       startIndex to endIndex - 1.
    */

    List lst = arrayList.subList(1,3);

    //display elements of sub list.
    System.out.println("Sub list contains : ");
    for(int i=0; i< lst.size() ; i++)
      System.out.println(lst.get(i));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.