本文介绍了Queue实现与圆阵:这是调整一个圆阵的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是圆形阵列实施队列,而且我有种陷在调整()方法实现(当数组已满)。

I'm implementing a queue using a circular array, and I'm kind of stuck in the resize() method implementation (when the array is full).

排队()方法我检查数组的大小等于它的长度,并获得它是否充分。现在,而不是抛出一个异常,我试图调整阵列。

Inside the enqueue() method I check if the size of the array equals it's length, and get if it's full. Now, instead of throwing an exception, I'm trying to resize the array.

问题是,我有两个问题需要注意。

The thing is, I have two cases to consider


  1. 前< =后面

  2. 后<前

这是对旧数组的元素复制到新的,更大的一个最佳方式?

Which is the best way to copy the elements of the old array into the new, larger one?

我认为它使用一个for循环,如:

I thought it using a for-loop, like:

newArray = new Array[oldArray.length*2];

if (front <= rear) {
    for (int i = front; i < rear; i++) {
        newArray[i] = oldArray[i];
    } 
} else {
    for (int i = front; i < newArray.length; i++) {
        newArray[i] = oldArray[i];
    }

    for (int j = rear; j < front; j++) {
        // i'm using the variable i, the order is maintained
        newArray[i] = oldArray[j];
        i++;
    }
}

然后 oldArray = newArray ,返回 newArray 和调整大小,它的完成

Then oldArray = newArray, return newArray and the resize it's done

我不知道的是用来做这个量,我怕我失去了价值。

I'm not sure of the amount of for's used to do this and I'm afraid I lose values.

谁能告诉我,如果有更好的方法来做到这一点?

Can someone tell me if there is a better way to do this?

推荐答案

有关超过了一把元素复制阵列,使用 System.arraycopy(),因为它通常是作为本地code,如实施Sun的虚拟机使用手工codeD汇编。

For copying arrays with more than a handful of elements, use System.arraycopy(), since it is usually implemented as native code, e.g. Sun's VM uses hand-coded assembler.

前>后

由于数据是连续的,它可以留在新阵列中的同一个地方。

Since the data is contiguous, it can remain in the same place in the new array.

System.arraycopy(oldArray, front, newArray, front, front-rear);

前&LT; =后面

的数据是不连续的,所以这两个块复制到新的数组的开始。

The data is non-contiguous, so copy both blocks to the start of the new array.

// copy [rear to end]
System.arraycopy(oldArray, rear, newArray, 0, oldArray.length-rear);
// copy [0 to front]
System.arraycopy(oldArray, 0, newArray, oldArray.length-rear, front);
front = oldArray.length-(rear-front);
rear = 0;

这篇关于Queue实现与圆阵:这是调整一个圆阵的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 05:57