java - 移动数组

标签 java arrays shift

我在一本书上看到这段代码,它的工作是数组移位。

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/

相关文章:

javascript - 使用类似于 php 的 javascript 向对象添加动态值

php - 在 PHP 中拆分数组的哪个函数更有效?

javascript - 在 JavaScript 中创建数据结构

javascript - Shift + 单击可选择一系列复选框

Java JNI 和 Vala - undefined symbol : g_once_init_enter

java - 在 apache/tomcat 设置 (mod_jk) 后面的 Vaadin 中获取 IP 地址总是给出服务器的 IP 地址

python - 对残差平方的numpy数组进行快速迭代

java - 我可以使用反射获取方法的局部变量的类对象吗

java - 如何水平对齐 JLabels 和 JTextFields?

python - 如何计算 Python Pandas 中组的移位列