blob: 62d42d3bb0aa5102620e73fdfbf92141031a4c62 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
package org.eclipse.net4j.util.collection;
import java.util.ArrayList;
/**
* A list with O(1) effort for random access.
*
* @author Eike Stepper
*/
public final class MoveableArrayList<E> extends ArrayList<E> implements MoveableList<E>
{
private static final long serialVersionUID = 1L;
public MoveableArrayList(int initialCapacity)
{
super(initialCapacity);
}
public E move(int targetIndex, int sourceIndex)
{
int size = size();
if (sourceIndex >= size)
{
throw new IndexOutOfBoundsException("sourceIndex=" + sourceIndex + ", size=" + size);
}
if (targetIndex >= size)
{
throw new IndexOutOfBoundsException("targetIndex=" + targetIndex + ", size=" + size);
}
E object = get(sourceIndex);
if (targetIndex == sourceIndex)
{
return object;
}
if (targetIndex < sourceIndex)
{
moveUp1(targetIndex, sourceIndex - targetIndex);
}
else
{
moveDown1(targetIndex, targetIndex - sourceIndex);
}
set(targetIndex, object);
return object;
}
private void moveUp1(int index, int count)
{
for (int i = count; i > 0; i--)
{
set(index + i, get(index + i - 1));
}
}
private void moveDown1(int index, int count)
{
for (int i = count; i > 0; i--)
{
set(index - i, get(index - i + 1));
}
}
}
|