java替换列表与子列表

时间:2011-10-13 22:27:25

标签: java list replace

我有一个清单

ArrayList list = new ArrayList(Arrays.asList(1,2,3,4,5,3,4,2,4,5,3,10));

我还有另一个子列表

ArrayList sublist = new ArrayList(Arrays.asList(4,5,3));

我正在寻找替代的功能 列表中的子列表

与另一个子列表

ArrayList sublist = new ArrayList(Arrays.asList(100,100)));

所以在查找和替换之后,新列表应该变为:

list = (1,2,3,100,100,4,2,100,100,10);

我在java中找不到任何api。

2 个答案:

答案 0 :(得分:3)

不确定是否存在任何api,但您可以做的是利用Java中的List接口。

如果你结合使用 containsAll(Collection c)           如果此列表包含指定集合的​​所有元素,则返回true。

removeAll(Collection c)           从此列表中删除指定集合中包含的所有元素(可选操作)。

addAll(int index,Collection c)           将指定集合中的所有元素插入到指定位置的此列表中(可选操作)。

我认为你可以很容易地完成你需要的东西。

看看这里: http://download.oracle.com/javase/6/docs/api/java/util/List.html

答案 1 :(得分:0)

如果您将子列表创建为list true 子列表,例如使用List#subList()sublist所做的(非结构性)更改将反映在list中。

List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 3, 4, 2, 4, 5, 3, 10);
List<Integer> sublist = list.subList(3, 6);

for (int i=0; i<sublist.size(); i++)
{
    sublist.set(i, 100);
}

System.out.println(sublist);
// prints 100, 100, 100
System.out.println(list);
// prints 1, 2, 3, 100, 100, 100, 4, 2, 4, 5, 3, 10

演示:http://ideone.com/ljvd0


Lists.newArrayList(...)来自Google Guava

相关问题