我有一个数组列表wilth values
ArrayList<String> HexValues = new ArrayList<String>();
HexValues.add("a");
HexValues.add("b");
HexValues.add("f");
HexValues.add("1");
HexValues.add("4");
HexValues.add("0");
HexValues.add("31");
HexValues.add("32");
HexValues.add("37");
System.out.println("The content of HexValues is: " + HexValues);
int start = HexValues.lastIndexOf("f");
if (start != -1) {
List<String> HexValuesEnd = HexValues.subList(start, HexValues.size());
System.out.println("The content of HexValuesEnd before leaving is: " + HexValuesEnd);
if (HexValuesEnd.size() > 0) {
HexValuesEnd.remove(1);
HexValuesEnd.remove(2);
HexValuesEnd.remove(3);
System.out.println("The content of HexValuesEnd after removing values at indexes 1 ,2,3: " + HexValuesEnd);
}
}
输出是
The content of HexValues is: [a, b, f, 1, 4, 0, 31, 32, 37]
The content of HexValuesEnd before leaving is: [f, 1, 4, 0, 31, 32, 37]
The content of HexValuesEnd after removing values at indexes 1 ,2,3: [f, 4, 31, 37]
但第二个数组列表中的预期值应为
"The content of HexValuesEnd after removing values at indexes 1 ,2,3: " [f,31,32,37]
我在哪里出错以获得预期的结果..
答案 0 :(得分:5)
当您删除其中一个值时,它后面的值会移动以填补间隙。
你的意思是
remove(1);
remove(1);
remove(1);
答案 1 :(得分:1)
这是因为
之后HexValuesEnd.remove(1);
arraylist是
[f,4,0,31,32,37]
现在执行
HexValuesEnd.remove(2);
所以你得到了
[f,4,31,32,37]
等等......您需要做的是
HexValuesEnd.remove(1);
HexValuesEnd.remove(1);
HexValuesEnd.remove(1);
答案 2 :(得分:0)
你有[f, 1, 4, 0, 31, 32, 37]
然后在索引1处删除并获取[f, 4, 0, 31, 32, 37]
然后索引2:[f, 4, 31, 32, 37]
(第一次删除后列表中的索引2为0
)
等等。
请注意,删除会更改列表。
似乎你想删除索引1
3次:
HexValuesEnd.remove(1);
HexValuesEnd.remove(1);
HexValuesEnd.remove(1);
答案 3 :(得分:0)
尝试
if (HexValuesEnd.size() > 0) {
HexValuesEnd.remove(1);
HexValuesEnd.remove(1);
HexValuesEnd.remove(1);
答案 4 :(得分:0)
最简单的方法是使用支持高阶滤波器方法的函数式编程库。我知道Apache-commons,Guava和lambdaJ都支持过滤器。
以下是关于synatx外观的一些sudo代码:
Predicate predicate = new Predicate(){{
public boolean evaluate(Object object){
// If statement comparison goes here
}
}};
filter(HexValuesEnd, predicate);
由于这是本机java,因此您需要创建一个谓词对象,以便对集合中的每个元素执行检查,并且每个库都有自己的方法来执行此操作。
Apache-commons和Gauva有自己的谓词对象,而lambdaJ建立在hamcrest之上,并使用它的匹配器作为谓词对象。
除了小的,高度可读的代码之外,还有一个额外的好处是这些库应该具有内置的并发优化,因此如果你想提高性能,你不必处理线程。
另外要注意.remove,如果你在一个循环中使用它,你将会有一个糟糕的时间。如果您想要迭代方法从集合中删除元素,请尝试使用迭代器。