ArrayList中的Java ArrayOutOfBoundException

Ura*_*rel 2 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;
}
Run Code Online (Sandbox Code Playgroud)

但我得到了一个ArrayOutOfBoundException.我究竟做错了什么?

Era*_*ran 5

更改

if(cluster.get(i-1) != a[i]) cluster.add(a[i]);
Run Code Online (Sandbox Code Playgroud)

if(a[i-1] != a[i]) cluster.add(a[i]);
Run Code Online (Sandbox Code Playgroud)

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