2

I have a collection List and i need to reverse order of it. Everything works fine with

List<Point> myList = new ArrayList<Point>();

i can reverse it with

Collections.reverse(myList); 

but this causes to allocate java.util.AbstractList$FullListIterator

i have about 5000 - 10000 paths to reverse in pathfinder and this causes GC to kick in.

How can i reverse this without any neccessary allocation ? I'm using generic pools whenever i can but i'm stuck with this.


You can simply loop on the length of the list and swap items at index i and (n-i-1). No allocation required.

int n = myList.size();
for (int i=n/2; i-->0;) {
    Object o = myList.get(i);
    myList.set(i, myList.get(n-i-1));
    myList.set(n-i-1, o);
}
4

5 回答 5

2

I would say, construct your datastructure in the way you don't have to loop again. By this I mean to say.. If you are reading this from a database, use order by clause

于 2012-08-16T07:27:30.640 回答
2

Try this:

int size = myList.size();
for (int i = 0; i < size / 2; i++) {
    Point temp = myList.get(i);
    myList.set(i, myList.get(size - i - 1));
    myList.set(size - i - 1, temp);
}

All this allocates is one reference to Point so that should be fine in your case.

于 2012-08-16T07:27:55.297 回答
1

Run the loop for half the size of list, it will be like swapping these first-with-last second-with-(last-1) third-with-(last-2) ...so on...

for(int i=0;i<list.size()/2;i++){           
    Object temp=list.get(i);
    list.set(i, list.get(list.size()-(i+1)));
    list.set(list.size()-(i+1), temp);
}
于 2012-08-16T07:33:02.717 回答
1

您可以简单地循环列表的长度并在索引i和交换项目(n-i-1)。无需分配。

int n = myList.size();
for (int i=n/2; i-->0;) {
    Object o = myList.get(i);
    myList.set(i, myList.get(n-i-1));
    myList.set(n-i-1, o);
}
于 2012-08-16T07:19:02.200 回答
0

Is an ArrayList absolutely necessary?

If reversing is your only important task, you can replace it with a java linked list, and get better performance both time-wise and space-wise.

于 2012-08-16T23:54:24.550 回答