选择大小为 N > L 的 ArrayList 的前 L 项并插入到 Java 中的另一个 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18313392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:24:44  来源:igfitidea点击:

Selection of First L Items of ArrayList of size N > L and Insertion to Another ArrayList in Java

javaarraylist

提问by NewJavaStudent

I have an ArrayList l1 of size N and another l2 of size L < N. I want to put the L first items of l1 to l2. I thought to use the for loop of type for(Object obj : l1) to scan my list of size N and then use l2.add(obj) to add elements on l2, but I am not sure if when I reach the max size of l2 (i.e. L) stops inserting items or continues.

我有一个大小为 N 的 ArrayList l1 和另一个大小为 L < N 的 l2。我想把 l1 的第 L 个项目放到 l2 中。我想使用 for(Object obj : l1) 类型的 for 循环来扫描我的大小为 N 的列表,然后使用 l2.add(obj) 在 l2 上添加元素,但我不确定何时达到最大大小的 l2 (即 L) 停止插入项目或继续。

Could somebody suggest me a way to do that? Thanx

有人可以建议我这样做吗?谢谢

回答by sanbhat

You can use List.subList(int, int)method to get the first L items

您可以使用List.subList(int, int)方法获取前 L 项

int L = 2;

List<String> newList = new ArrayList<>(inputList.subList(0,L));

回答by AlexR

Something like the following:

类似于以下内容:

    list2.addAll(list1.subList(0, l));

回答by hkara

Use System.arraycopy()

使用 System.arraycopy()

Here an example :

这里有一个例子:

package test_temp;

public class TestArrayCopy
{

  public static void main(String[] args) {
    String[] SRC = {"Hello", "all", "you", "happy", "taxpayers"};
    int dimN = SRC.length;
    int dimL = 4;
    String[] dest = new String[dimL];
    System.arraycopy(SRC, 0, dest, 0, Math.min(dimN, dimL));
    for (int i = 0; i < dimL; i++) System.out.println(dest[i]);
  }

}

This will give the following output :

这将提供以下输出:

Hello
all
you
happy

Hope this is wat you expected ?

希望这是你所期望的?