gpt4 book ai didi

java - 如何将 ArrayList 添加到另一个 ArrayList 之前?

转载 作者:行者123 更新时间:2023-12-01 06:27:52 24 4
gpt4 key购买 nike

我希望将 java.util.ArrayList L1 的元素前置到另一个 java.util.ArrayList L2 中,但我不能找到一种开箱即用的方法来做到这一点。我不想创建第三个 ArrayList 并进行修改,因为 L2 是 View 层中使用的列表。 java.util.Collections 和 org.apache.commons.collections.CollectionUtils 都没有这样的实用方法(据我所知)。

如何有效地将一个 ArrayList 附加到另一个 ArrayList 之前,最好使用现有的 API?对于 java 7 环境。

P.S: addAll 附加,我想前置。

最佳答案

使用List#addAll(int,Collection) :

Inserts all of the elements in the specified collection into this list at the specified position (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in this list in the order that they are returned by the specified collection's iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list, and it's nonempty.)

如果您使用0作为索引,它将把给定的Collection添加到List中。例如:

import java.util.ArrayList;
import java.util.List;

public class Main {

public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();

list1.add("Item #1");
list1.add("Item #2");

list2.add("Item #3");
list2.add("Item #4");

System.out.println("List #1: " + list1);
System.out.println("List #2: " + list2);

list2.addAll(0, list1);

System.out.println("Combined List: " + list2);

}
}

输出:

List #1: [Item #1, Item #2]
List #2: [Item #3, Item #4]
Combined List: [Item #1, Item #2, Item #3, Item #4]

关于java - 如何将 ArrayList 添加到另一个 ArrayList 之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58479663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com