Combining an array's index 0 with 1, 2 with 3, 4 with 5

寵の児 提交于 2019-12-11 11:44:24

问题


For example, in an array

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

I want the code to produce an output of

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

What I have so far:

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);    
    }
}

回答1:


Your current code will throw an OutOfBoundsException because it is not checking if the list holds a value in the index while looping.

A good way to do that is to initialize a list that will hold the concatenated values.

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:


try creating a new list to add to

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;
}



回答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;
}


来源:https://stackoverflow.com/questions/24749146/combining-an-arrays-index-0-with-1-2-with-3-4-with-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!