A simple swap is much better for "moving something" in an ArrayList:
if(i > 0) { Item toMove = arrayList.get(i); arrayList.set(i, arrayList.get(i-1)); arrayList.set(i-1, toMove); }
Since an ArrayList uses an array, if you delete an element from an ArrayList, it must βshiftβ all the elements after that element up to fill the gap in the array. If you insert an element, it must move all the elements after that element to make room for it to be inserted. These shifts can become very expensive if your array is very large. Since you know that you want to get the same number of elements in the list, such a swap allows you to very effectively "move" an element to another place in the list.
As Chris Buckler and Michal Kreitzman emphasizes, there is even a convenient method in the Collections class that reduces these three lines of code to one:
Collections.swap(arrayList, i, i-1);
StriplingWarrior Feb 08 2018-11-11T00: 00Z
source share