【问题标题】:Combining an array's index 0 with 1, 2 with 3, 4 with 5将数组的索引 0 与 1、2 与 3、4 与 5 组合
【发布时间】:2014-07-15 02:52:13
【问题描述】:

例如,在数组中

["1", "2", "3", "4", "5", "6", "7"]

我希望代码产生

的输出
["1 2", "3 4", "5 6", "7"]

到目前为止我所拥有的:

public static void combine(ArrayList<String> list) {
    for (int i = 0; i < list.size(); i++) {
            String a0 = list.get(i);
            String a1 = list.get(i + 1);
            String a2 = a0 + a1;
            if (list.get(i + 1) == null) {
                a2 = a1;
            }
            list.remove(i);
            list.remove(i + 1);
            list.add(i, a2);    
    }
}

【问题讨论】:

  • 你是如何“组合”这些的?为什么 4 翻倍,而 6 发生了什么?
  • 它现在产生什么输出?您的代码面临的确切问题是什么?
  • String a1 = list.get(i + 1); 为包含奇数个项目的列表最后一次运行时,您将得到一个异常。
  • @user3748593 我终于用 java 8 中的 lambda 表达式解决了这个问题

标签: java concatenation


【解决方案1】:

您当前的代码将抛出 OutOfBoundsException,因为它在循环时不检查列表是否在索引中保存值。

这样做的一个好方法是初始化一个将保存连接值的列表。

public static ArrayList<String> combine(ArrayList<String> list) {
    ArrayList<String> newList = new ArrayList<>();

    for (int i = 0; i < list.size(); i = i + 2) {
        // get first number
        String firstNumber = list.get(i);

        // check if second number exists
        if (i + 1 < list.size()) {
            String secondNumber = list.get(i + 1);
            // add concatenated string to new list
            newList.add(firstNumber + " " + secondNumber);
        } else {
            // no second number exists, add the remaining number
            newList.add(firstNumber);
        }
    }

    return newList;
}

【讨论】:

    【解决方案2】:

    尝试为add创建一个新列表

    public static void combine(ArrayList<String> list) {
    
        ArrayList <String> nl = new ArrayList<> ();
    
        for (int i = 0; i < list.size(); i = i + 2) {
    
            String a0 = list.get(i);
            if (i + 1 < list.size()) {
                String a1 = list.get(i + 1);
                nl.add(a0 + " " + a1);  
            } else {
                nl.add(a0);  
            }
        }
    
        list = nl;
    }
    

    【讨论】:

    • 为什么需要在循环范围之外定义i?如果您仍然创建一个新列表,为什么不返回它?
    • nl.add(i, a0); 会抛出一个OutOfBoundsException。也许只是使用n1.add(a0)
    • @PM77-1 是的,没有理由在 lopp 之外定义 i - 已修复。保持方法签名与 OP 相同,但我个人也会返回它。
    • @khakiout 改用普通的add 方法 - 太想吃我的午餐了 ;-)
    【解决方案3】:
    public static ArrayList<String> combine(ArrayList<String> list) {
        ArrayList<String> newList = new ArrayList<String>(list.size()/2);
        for (int i = 0; i < list.size()-1; i= i+2) {
                String a0 = list.get(i);
                String a1 = list.get(i + 1);
                String a2 = a0 + a1;
                newList.add(a2);
    
        }
        if(list.size()%2 == 1)
            newList.add(list.get(list.size()-1));
    
        return newList;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多