我需要遍历 arraylist 并将所有以 x
y
或 z
开头的单词删除到前面。
但是我的测试输出表明该方法存在一些逻辑错误。
代码:
/**
* Moves any word that startw with x, y, or z to the front of the arraylist, but
* otherwise preserves the order
*/
public void xyzToFront()
{
int insertAt = 0;
but otherwise preserves the order
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i);
if (temp.startsWith("x") || temp.startsWith("y") || temp.startsWith("z")) {
list.remove(i);
list.add(0, temp);
}
}
}
测试输出:
Actual: [yak, zebra, xantus, ape, dog, cat] - what is after executing
Expected: [xantus, zebra, yak, ape, dog, cat] - what we should have
如何解决这个问题?
最佳答案
根据您的方法,该方法在上一个之前插入以 x、y 或 z 开头的每个下一个单词以及实际和预期的输出,我认为您希望将单词按照删除的顺序插入到列表的前面。如果是这种情况,您可以使用计数器变量并在先前删除后插入下一个单词。例如:
public void xyzToFront()
{
int insertAt = 0;
but otherwise preserves the order
for (int i = 0; i < list.size(); i++) {
if (temp.startsWith("x") || temp.startsWith("y") || temp.startsWith("z")) {
String temp = list.get(i);
list.remove(i);
list.add(insertAt++, temp);
}
}
}
关于java - 将任何以 x、y 或 z 开头的单词移动到数组列表的前面 - 错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17503980/