Java ArrayList 中的 ArrayOutOfBoundException

标签 java arrays arraylist

问题是将整数数组中的簇定义为全部相同值的元素的最大序列。例如,数组 {3, 3, 3, 4, 4, 3, 2, 2, 2, 2, 4} 有 5 个簇, {3, 3, 3 }{4, 4}{3}{2, 2, 2, 2} {4}。数组的簇压缩将每个簇替换为簇中重复的数字。因此,前一个数组的簇压缩将为 {3, 4, 3, 2, 4}。第一个簇 {3, 3, 3} 被单个 3 替换,依此类推。

public static void  main(String[] args) {

    int[] givenArray = {1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1};
    System.out.println("Clustered Array = " + Arrays.toString(isTrivalent(givenArray)));
}

public static int[] isTrivalent  (int[] a){

    List<Integer> cluster = new ArrayList<Integer>();

    for (int i=0; i<a.length ; i++ ) {

        if(i == 0){
            cluster.add(a[i]);
        }else{
            if(cluster.get(i-1) != a[i]) cluster.add(a[i]);
        }
    }

    int[] arr = new int[cluster.size()];

    for (int j =0; j<cluster.size() ; j++) {
        arr[j] = cluster.get(j);
    }

    return arr;
}

但是我收到了ArrayOutOfBoundException。我做错了什么?

最佳答案

改变

if(cluster.get(i-1) != a[i]) cluster.add(a[i]);

if(a[i-1] != a[i]) cluster.add(a[i]);

cluster.get(i-1) 可能不存在。

关于Java ArrayList 中的 ArrayOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30502562/

相关文章:

java TwitterAuthClient onActivityResult

java - 在路径中找不到 Eclipse 错误 'g++/gcc'

java - java中使用ArrayList的indexOf()

java - 如何在实例化类数组列表中添加元素

python - 并非所有满足条件的元素都会被删除

java - java中的扫描仪问题

java - 添加 View 后无法刷新布局(仅发生在 CustomAdapter 中)

c - 在 C 中遍历数组

javascript - 获取动态生成的 div 的索引位置并存储在数组中,其中包含 onclick 函数

arrays - 通过动态构造的变量名称间接分配给bash数组变量