java - ArrayList操作

标签 java arraylist data-structures

但是如何?

这是需要添加到类中的四个方法:

1.void deleteRange(int fromIndex,int toIndex):从此列表中删除其索引介于fromIndex(包括)和toIndex(不包括)之间的所有元素。

2.void deleteAll(String str):从列表中删除所有值为str的元素。

3.int indexOf(String str):该方法返回给定元素的第一次出现,或者如果元素不在列表中则返回-1。

4. int lastIndexOf(String str):该方法返回给定元素的最后一次出现,或者如果元素不在列表中则返回-1。

最佳答案

如果ArrayList.removeRange()符合您要执行的操作,则可以通过创建一个新的protected来解决ArrayList限制,该新的包含第一个和最后一个子列表,但不包括中间的范围。

这是一个例子:

ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "zero", "one", "two", "three", "four");

List<String> manipulatedList = new ArrayList<>(list.size());
int removeStartIndex = 2;
int removeEndIndex = 4;

List<String> firstSubList = list.subList(0, removeStartIndex);
manipulatedList.addAll(firstSubList);

List<String> lastSubList = list.subList(removeEndIndex, list.size());
manipulatedList.addAll(lastSubList);

System.out.println("list        : " + list.toString());
System.out.println("manipulated : " + manipulatedList.toString());


当我在本地运行该命令时,这是输出-元素“两个”和“三个”已从操作列表中删除:

list        : [zero, one, two, three, four]
manipulated : [zero, one, four]

关于java - ArrayList操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58159240/

相关文章:

java - 重新格式化 CSV 输入文件

java - 将所有 JSON 值转换为字符串

java - 在 Joda-Time 中,将 DateTime 设置为月初

Java 正则表达式 : How to return the whole word if the words ends with a specific string

java - 如何从内循环中迭代数组列表,每次都会指向下一个地址元素

algorithm - 具有高效查找缺失的一组键的数据结构

java - 用于匹配引号内模式的正则表达式

c# - 将 List<string> 转换为 ArrayList

算法分析-渐近分析

python - 直观理解 Numpy nd 数组