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 !
For the swap operation you call add
when you should use set
. So you are increasing the list endlessly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.