java - 将任何以 x、y 或 z 开头的单词移动到数组列表的前面 - 错误的输出

标签 java arraylist

我需要遍历 arraylist 并将所有以 x yz 开头的单词删除到前面。

但是我的测试输出表明该方法存在一些逻辑错误。

代码:

/**
   * 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/

相关文章:

java - 当对象没有相同的引用时从 ArrayList 中删除重复项

java - 如何设置为int值null? Java 安卓

java - Java中按对象类型对对象列表进行排序

java - 抽象类如何返回子类对象的ArrayList?

java - 访问List<List<List<List<Object>>>> titles = new ArrayList<List<List<Object>>>>();

java - C++ 列出用法

java - Java 中数组的 ArrayList 到 2d 数组

Java - System.out 对性能的影响

java - JTextPane 是 JScrollPane 可接受的客户端吗?

java - Spring Boot应用中 "Whitelabel Error Page"相关问题如何解决