压缩 ArrayList 方法中的错误

我正在尝试用 Java 编写一个方法来压缩字符串的 ArrayList。例如,如果我们有一个由 String 组成的 ArrayList ["0", "1", "2", "3"],则会ArrayListMethods.condense(["0", "1", "2", "3"])将 ArrayList 更改为["01", "23"]。


import java.util.ArrayList;


public class ArrayListMethods

{

  public static void condense(ArrayList<String> array){

        for (int i = 0; i < array.size(); i++){

            array.get(i) += array.get(i + 1);

            array.remove(i + 1);

        }

  }

}

我收到错误,但我不知道为什么。


没关系,问题解决了。我像这样重写了代码:


public static void condense(ArrayList<String> array){

        for (int i = 0; i < array.size() - 1; i++){

            String one = array.get(i);

            String two = array.get(i+1);

            String both = one+two;

            array.set(i, both);

            array.remove(i + 1);

        }

    }


慕姐4208626
浏览 46回答 2
2回答

幕布斯6054654

如果你确定元素的数量总是偶数,你可以这样做:public static void condense(ArrayList<String> array){&nbsp; &nbsp; for (int i = 0; i < array.size(); i++){&nbsp; &nbsp; &nbsp; &nbsp; array.set(i, array.get(i)+array.get(i + 1));&nbsp; &nbsp; &nbsp; &nbsp; array.remove(i + 1);&nbsp; &nbsp; }}更好的方法是这样的:public static void condense2(List<String> list){&nbsp; &nbsp; int groupSize = 2;&nbsp; &nbsp; List<String> result = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for (int i = 0; i < list.size(); i += groupSize) {&nbsp; &nbsp; &nbsp; &nbsp; result.add(String.join("", list.subList(i,Math.min(i + groupSize, list.size()))));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(result);}使用第二种方法,您不仅限于连接两个字符串,通过更改 groupSize 您可以实现类似的["012", "345", "6"]输入["0","1","2","3","4","5","6"]

沧海一幻觉

array.get(i) 不是变量,它是String在您的情况下返回的方法调用。您无法为其分配任何内容。你可能想要类似的东西array.set(i, array.get(i + 1))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java