1

我有一个当前列表,我希望通过用另一个列表替换一系列元素来更新它,例如:

当前列表:

a, b, c, d, e, f, g

新列表:

x, y, z

我想做类似于以下的事情:

CurrentList.setAll(5, NewList)

哪个应该将 转换CurrentList为具有以下值:

a, b, c, d, e, x, y, z

所以它用一个额外的新元素替换了f, g元素。x, yaddedCurrentListz

编辑:这并不总是在列表的末尾。它不仅与字符串有关。这是关于具有任何类型元素的列表。这需要适用于列表的任何部分。例如我可能需要更换b, c, d. 我只是有起始索引,然后我必须向前替换元素,如果列表空间不足,则add列出而不是替换。

4

2 回答 2

4

如果您有一组字母,最好使用 StringBuilder

StringBuilder sb = new StringBuilder("abcdefg");
sb.replace(5, sb.length(), "xyz");

如果你有一个元素列表,你可以做

List<String> list = ...
List<String> subList = list.subList(5, list.size());
subList.clear();
subList.addAll(Arrays.asList("x", "y", "z"));
于 2012-12-13T18:14:43.167 回答
2

你正在寻找的是这个:

List<?> list = ...  // original list
List<?> toReplace = list.subList(startingIndex, endIndex);
toReplace.clear(); // clears the subList
List<?> replacement = ... // list of new elements
toReplace.addAll(replacement); // inserts the new elements in the original list, through the sublist

您也可以一一添加新元素。支持列表将根据需要增加大小。

于 2012-12-13T18:29:18.777 回答