我尝试将数组tempo
的值复制到newPosition
,但当tempo
被getObjectPosition()
方法更改时,newPosition
一直在更改。这是我的代码。
private int[] newPosition = new int[2];
private int[] oldPosition = new int[2];
private int[] tempo = new int[2];
private int theId, objectSpeed
private boolean threadInitialized = false;
while(this.getObjectMagnitude() > 0) {
tempo = this.getObjectPosition();
if(!this.notification) {
System.out.println("Hostile Object Identified! Tracking in progress.....");
Arrays.fill(this.onOffSwitch,false);
investigatePatterns.submit(analyseFutures);
this.notification = true;
}
if(this.init_pos) {
this.newPosition = this.tempo.clone();
this.newAndOldTime[1] = System.currentTimeMillis();
this.init_pos = false;
}
else if(!this.init_pos) {
System.out.println(this.newPosition[0]+"," +this.newPosition[1]+" and "+
this.tempo[0] + "," + this.tempo[1]
);
if(!(Arrays.equals(this.newPosition, this.getObjectPosition()))) { //do other stuff }
}
}
我还尝试了其他方法,如System.arraycopy()
和实现for
循环,但都不起作用。
下面是getObjectPosition
方法
private int[] getObjectPosition() {
return MainThread.theObject[this.theId].getPosition();
}
这里我漏掉了什么?
我现在正在使用这个循环。,,。它起作用了
private static int[] fullCopy(int[] source) {
int[] destination = new int[source.length];
String e, f, g = "0";
for(int i=0; i< source.length; i++) {
f = Integer.toString(source[i]);
for(int k=0; k<f.length();k++)
{
for(int h=0; h<10; h++) {
e = Integer.toString(h);
if((f.charAt(k)) == (e.charAt(0)))
g = g + (e.charAt(0));
}
}
destination[i] =Integer.valueOf(g);
g = "0";
}
return destination;
}
发布于 2018-09-17 01:20:58
Array.clone复制对数组的引用,因此对数组中一个元素的任何更改都会导致对另一个数组的相应引用的更改。您要做的是复制数组的值。为此,我建议创建一个循环来遍历A数组中的每个索引,并将其分配给B数组中的相同索引。
另外,作为对布尔条件的附带说明,您不需要
if(bool == true)
相反,您可以这样做
if(bool)
和用于检查假值的do
if(!bool)
System.arraycopy示例:
void runExample(){
//show before
printArrays();
//copy array values
System.arraycopy(originalArray, 0, copiedArray, 0, originalArray.length);
//show after copy
printArrays();
//change original values
for (int i = 0; i < originalArray.length; i++){
originalArray[i] = i;
}
//show values after change
printArrays();
}
这样做的结果是:
原始数组: 4,2复制数组: 0,0
原始数组: 4,2拷贝数组: 4,2
原始数组: 0,1复制数组: 4,2
https://stackoverflow.com/questions/52356464
复制相似问题