Java的:移位/对象数组 [英] Java: Shift/Rotate Object Array

查看:138
本文介绍了Java的:移位/对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题实际上应该是很简单的:
我有玩家的对象数组(玩家[])
我想有这种旋转直到数组的索引功能:

My question should actually be really simple: I have an object array of Players.(players[]) I want to have a function that rotates this array until an index:

public void rotateArray(Object[] array, int index)

这将转换

{Player1, Player2, Player3, Player4, Player5}

为2到索引

{Player3, Player4, Player5, Player1, Player2}

但我想美元,引用p $ pvent问题。
我试过System.arraycopy(),但无论是我还是哑巴得到它的工作或我是这个错误的方法。

But I want to prevent issues with references. I've tried System.arraycopy() but either I was to dumb to get it working or I is the wrong method for this.

推荐答案

有必要让数组的副本使用arraycopy,我建议,因为它应该是最快的。避免副本的唯一原因是,如果数组是非常大的内存很紧张。

It will be necessary to make a copy of the array to use arraycopy, which I recommend as it should be the fastest. The only reason to avoid a copy is if the array is very large and memory is tight.

public void rotateArray(Object[] array, int index)
{
    Object[] result;

    result = new Object[array.length];

    System.arraycopy(array, index, result, 0, array.length - index);
    System.arraycopy(array, 0, result, array.length - index, index);

    System.arraycopy(result, 0, array, 0, array.length);
}

这篇关于Java的:移位/对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆