ArrayList中的Java ArrayOutOfBoundException

时间:2015-05-28 09:30:46

标签: 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。我做错了什么?

2 个答案:

答案 0 :(得分:5)

更改

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)可能不存在。

答案 1 :(得分:1)

这种情况正在发生,因为当您检查

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

群集arraylist实际上不必具有至少i-1的大小,因为您正在跳过大量的数组元素。您需要将条件更改为

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

或等效(如先前回答中所述)

if(a[i-1] != a[i])

此代码按预期工作。

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(cluster.size() - 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;
}