liuz_m
liuz_m

Reputation: 11

Reverse order of the Arrays stored in ArrayList

I'm working with Processing and IGeo library and I have an ArrayList of IVec[] arrays:

ArrayList<IVec []> v = new ArrayList<IVec[]>(); 

For every I of the ArrayList I have a collection of IVec [] arrays that represent the coordinates of the control points of a curve. I need to reverse the order of the IVec [] control points keeping the same order of the ArrayList (I'm trying to invert curve seam reversing control points order and keeping the original order of the curves) but I can't understand how to do this. Can anyone help me?

Upvotes: 0

Views: 147

Answers (5)

Chaos Monkey
Chaos Monkey

Reputation: 984

This should work (not the most efficient way, but easily understood):

public static <T> void reverseElements(ArrayList<T[]> list) {   

    ArrayList<T> tempList = new ArrayList<T>();
    for(T[] arr : list) {

        tempList.clear();
        for(T t : arr)
            tempList.add(t);

        Collections.reverse(tempList);
        tempList.toArray(arr);
        arr = tempList.toArray(arr);
    }       
}

Upvotes: 0

Want2bExpert
Want2bExpert

Reputation: 527

Try this;

  • Create a Helper method/function that takes and returns array.
  • Inside the Helper method, use Collections.reverse
  • return the reversed array.
  • call this helper method inside a loop as below:
for(int i = 0; i < OutArray.length; I++)
{ // Here get the inner Array and pass it to Helper method. 
// Add the return array to newArray List 
}
return newArrayList.

Upvotes: 0

liuz_m
liuz_m

Reputation: 11

This solution is working:

for (int i=0; i<v.size (); i++) {  
  IVec [] vert=v.get(i); 
  for (int j=0; j<vert.length/2; j++) {
    IVec temp = vert[j];
    vert[j]=vert[vert.length -1 - j];
    vert[vert.length - 1 - j] = temp;
  }
}

Upvotes: 0

code_dredd
code_dredd

Reputation: 6085

You can use Collections.reverse

You can also use a stack data structure. You can iterate over collection you wish to reverse by pushing the elements into the stack. Then, when you actually want to use the elements, you pop each element from the stack, which will allow you to iterate over the collection in reverse order.

Upvotes: 1

Maroun
Maroun

Reputation: 95968

I won't provide you a full solution, but will guide you through it:

  • Iterate on the array list v
  • for each item in it (IVec[]),

Upvotes: 1

Related Questions