简体   繁体   中英

Retrieving elemnts from an ArrayList by specifying the indexes

是否有Java中的方法通过指定开始和结束索引来获取从Arraylist到另一个ArrayList的对象列表?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM