【问题标题】:Retrieving elemnts from an ArrayList by specifying the indexes通过指定索引从 ArrayList 中检索元素
【发布时间】:2012-08-06 12:12:11
【问题描述】:

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

【问题讨论】:

    标签: java arraylist indexing


    【解决方案1】:

    是的,您可以使用subList method

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

    这会返回原始列表那部分的视图,它不会复制数据。
    如果你想要一份副本:

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

    【讨论】:

    • 没错,但请注意对对象的引用保持不变。因此,如果您更改 subList 中的对象,它们也会在第一个列表中更改。
    • @Chris 是的,第二个版本不是深拷贝,它只复制对象的引用。
    【解决方案2】:
    /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));
    

    【讨论】:

      猜你喜欢
      • 2015-08-15
      • 2021-01-06
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 1970-01-01
      相关资源
      最近更新 更多