我会使用这种简单的方法来旋转数组(我认为该方法应该称为rotate 而不是replaceAll,因为它实际上是将数组旋转了一个位置)。
这是rotate()的方法:
@SuppressWarnings("unchecked")
public void rotate() {
Object[] temp = new Object[theData.length];
//copy each element, except the first, from theData into temp by shifting one position off to the right
for (int i = temp.length - 1; i > 0; i--) {
temp[i] = theData[i - 1];
}
//move the last element into the first position
temp[0] = theData[theData.length - 1];
//update theData
theData = (T[]) temp;
}
完整的可测试示例
public class MyArrayList<T> {
int INITIAL_CAPACITY = 10;
int capacity;
T[] theData;
@SuppressWarnings("unchecked")
public MyArrayList() {
capacity = INITIAL_CAPACITY;
theData = (T[]) new Object[capacity];
}
@SuppressWarnings("unchecked")
public MyArrayList(int capacity) {
this.capacity = capacity;
theData = (T[]) new Object[this.capacity];
}
@SuppressWarnings("unchecked")
public void rotate() {
Object[] temp = new Object[theData.length];
//copy each element, except the first, from theData into temp by shifting one position off to the right
// to the right
for (int i = temp.length - 1; i > 0; i--) {
temp[i] = theData[i - 1];
}
// move the last element into the first position
temp[0] = theData[theData.length - 1];
// update theData
theData = (T[]) temp;
}
/**
* For testing purposes only. It doesn't handle out of bounds values of
* index.
*/
private void insert(T t, int index) {
theData[index] = t;
}
public void print() {
for (T t : theData) {
System.out.print(t + ", ");
}
System.out.println();
}
@SafeVarargs
public static <E> MyArrayList<E> of(E... elements) {
MyArrayList<E> m = new MyArrayList<>(elements.length);
for (int i = 0; i < elements.length; i++) {
m.insert(elements[i], i);
}
return m;
}
}
测试rotate()方法:
public class TestMyArrayList {
public static void main(String[] args) {
MyArrayList<Integer> m = MyArrayList.of(1, 2, 3, 4, 5);
m.print();
m.rotate();
m.print();
}
}
它会打印出来:
1, 2, 3, 4, 5,
5, 1, 2, 3, 4,