Retrieving elemnts from an ArrayList by specifying the indexes

后端 未结 2 1741
感动是毒
感动是毒 2020-12-18 00:05

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条回答
  •  别那么骄傲
    2020-12-18 00:11

    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));
    

提交回复
热议问题