Uraz Pokharel
Uraz Pokharel

Reputation: 210

Java ArrayOutOfBoundException in ArrayList

The question is Define a cluster in an integer array to be a maximum sequence of elements that are all the same value. For example, in the array {3, 3, 3, 4, 4, 3, 2, 2, 2, 2, 4} there are 5 clusters, {3, 3, 3}, {4, 4}, {3}, {2, 2, 2, 2} and {4}. A cluster-compression of an array replaces each cluster with the number that is repeated in the cluster. So, the cluster compression of the previous array would be {3, 4, 3, 2, 4}. The first cluster {3, 3, 3} is replaced by a single 3, and so on.

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

But I am getting an ArrayOutOfBoundException. What am I doing wrong?

Upvotes: 2

Views: 741

Answers (2)

Bhoot
Bhoot

Reputation: 2633

This is happening because when you check

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

it is not necessary that the cluster arraylist will actually have size of atleast i-1 since you are skipping a lot of array elements. You need to change your condition to

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

or equivalently (as suggested in previous answer)

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

for this code to work as intended.

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

Upvotes: 1

Eran
Eran

Reputation: 393811

Change

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

to

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

cluster.get(i-1) may not exist.

Upvotes: 5

Related Questions