0

I have written a method which sorts the arrayList and them swaps the consecutive elements in that arrayList. I am facing a issue -

If I implement the method by using Collections.sort() it gives heapsize error while if I use Arrays.sort() it does not and run successfully.

public ArrayList<Integer> sortAndSwap(ArrayList<Integer> a) {
       Collections.sort(a);
        for(int i = 0; i < a.size()-1; i+=2) {
            int temp = a.get(i);
            a.add(i, a.get(i+1));
            a.add(i+1, temp);
        }
        return a;
    }

this method gives the below error -

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:3210) at java.util.Arrays.copyOf(Arrays.java:3181) at java.util.ArrayList.grow(ArrayList.java:261) at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235) at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227) at java.util.ArrayList.add(ArrayList.java:475) at Solution.wave(Solution.java:7) at Main.main(Main.java:322)

while if i modify it as follows

public ArrayList<Integer> sortAndSwap(ArrayList<Integer> a) {
        Integer []arr = new Integer[a.size()];
        a.toArray(arr);
        Arrays.sort(arr);
        for(int i = 0; i < a.size()-1; i+=2) {
            int temp = arr[i];
            arr[i] = arr[i+1];
            arr[i+1] = temp;
        }
        a = new ArrayList<Integer>(Arrays.asList(arr));
        return a;
    }

It runs fine and gives desired results. Why is this happening, can anybody explain ? Thanks !

1 Answer 1

6

For the swap operation you call add when you should use set. So you are increasing the list endlessly.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ! it worked. One more thing, if Arrays.sort() and Collections.sort() are equally efficient?
Collections.sort() is based on Arrays.sort() but adds the overhead of creating a temporary array from the list.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.