我在一本书上看到这段代码,它的工作是数组移位。
public void arrayshift(int count) {
synchronized (array) {
System.arraycopy(array, count, array, 0, array.length - count);
}
}
现在我像往下一样运行这段代码,但是结果是错误的!
public class t2 {
static byte array[] = new byte[]{1, 2, 3, 4, 5, 6};
public void arrayshift(int count) {
synchronized (array) {
System.arraycopy(array, count, array, 0, array.length - count);
}
}
public static void main(String[] args) {
System.out.println("First array: " + Arrays.toString(array));
new t2().arrayshift(2);
System.out.println("After two shift is: " + Arrays.toString(array));
}
}
结果:
First array: [1, 2, 3, 4, 5, 6]
After two shift is: [3, 4, 5, 6, 5, 6]
最佳答案
要实际旋转,还有一种替代方法,即使用 Collections.rotate()
在您的情况下,您可以转换 byte[]
至 Byte[]
,创建字节列表并使用 Collections.rotate()
旋转
下面是一种快速而肮脏的方法,与您所做的保持接近。
您修改后的代码:
static byte array[] = new byte[] { 1, 2, 3, 4, 5, 6 };
static List<Byte> list = new ArrayList<Byte>();
public static void main(String[] args) {
System.out.println("First array: " + Arrays.toString(array));
new Rotate().arrayshift(2);
System.out.println("After two shift is: ");
for (Byte b : list.toArray(new Byte[list.size()]))
System.out.print(b.byteValue() + ", ");
}
public void arrayshift(int count) {
synchronized (array) {
Byte[] byteObjects = new Byte[array.length];
int i = 0;
for (byte b : array)
byteObjects[i++] = b;
list = Arrays.asList(byteObjects);
Collections.rotate(list, count);
}
}
输出:
First array: [1, 2, 3, 4, 5, 6]
After two shift is:
5, 6, 1, 2, 3, 4,
关于java - 移动数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21001923/