简体   繁体   English

为什么我不能在java中复制数组的一部分?

[英]Why can't I copy a section of an array in java?

I'm new to java, but have done some programming in other languages before. 我是java的新手,但之前已经用其他语言做过一些编程。 I have an array that I declared. 我有一个我声明的数组。 This one is for the basic equipment, and each of the basicSimple* have been correctly declared earlier on: 这个是基本设备,每个basicSimple *都已在前面正确声明:

//Creating template...
Item[] basicSet = new Item[15];
basicSet [0] = basicSimpleShoes;
basicSet [2] = basicSimplePants;
basicSet [4] = basicSimpleShirt;
basicSet [6] = basicSimpleGloves;

I'm trying to copy the array to some other ones, each for one of the possible formats, one of which looks like this: 我正在尝试将数组复制到其他一些数组,每个数组都有一种可能的格式,其中一种看起来像这样:

//Strongarm set...
Item[] strongarmBeginnerSet = new Item[15];
strongarmBeginnerSet [0,6] = basicSet[0,6];
strongarmBeginnerSet [9] = basicSimpleShortsword;
strongarmBeginnerSet [10] = basicSimpleShield;

Again, the basicSimple* Items are correctly declared earlier on. 同样,basicSimple * Items在之前正确声明。 I keep on getting an error, something about a missing closing bracket, but I can't find where it is. 我继续得到一个错误,一个关于缺少结束括号的东西,但我找不到它的位置。 Do I have to declare each piece individually or is there a function I'm unaware of for this scenario? 我是否必须单独声明每个部分,或者是否有一个我不知道这个场景的功能?

This simply won't work in Java, the slice notation exists for other programming languages (say, Python), but not in Java: 这根本不适用于Java,其他编程语言(比如Python)的切片表示法存在,但Java不存在:

strongarmBeginnerSet[0,6] = basicSet[0,6]; // compiler reports a syntax error!

You have to copy each element in turn, like this (and I'm assuming that you intended to copy up to and including the seventh element located at index 6 ): 您必须依次复制每个元素(我假设您打算复制到包含位于索引6的第七个元素):

for (int i = 0; i < 7; i++)
    strongarmBeginnerSet[i] = basicSet[i];

Or alternatively, use System.arraycopy() : 或者,使用System.arraycopy()

System.arraycopy(basicSet, 0, strongarmBeginnerSet, 0, 7);

strongarmBeginnerSet [0,6] = basicSet[0,6]; is not valid syntax in Java. 在Java中不是有效的语法。 You will need to use a for loop instead. 您将需要使用for循环。

strongarmBeginnerSet [0,6] = basicSet[0,6]; is invalid syntax for Java. 是Java的无效语法。

You could use System.arraycopy to achieve the same result... 您可以使用System.arraycopy来实现相同的结果......

Something like... 就像是...

System.arraycopy(basicSet, 0, strongarmBeginnerSet, 0, 6);

For example... 例如...

要复制数组的一部分,请使用:

strongarmBeginnerSet [6] = Arrays.asList(basicSet).subList(0,7).toArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM