我试图让数组位置被交换,但它不起作用。无论我做什么,我都无法让它们被交换,我知道这与我编写if语句的方式有关。
以下是主要代码:
Comparable[] computerSizes = new Comparable[3];
int a = computerSizes.length - 1;
computerSizes[0] = new Desktop("i5","Desktop",4,1024,250);
computerSizes[1] = new Desktop("i3","Desktop",6,512,350);
computerSizes[2] = new Laptop(15.6,"i3","Laptop",4,0,750);
for (int i = 0; i < a;i++) {
if(computerSizes[i].compareTo(computerSizes[i+1]) == 1){
computerSizes[i] = computerSizes[i+1];
computerSizes[i+1] = computerSizes[i];
}//end if
System.out.println(computerSizes[i]);
}//end for
以下是相关的compareTo方法代码:
public int compareTo(Comparable c)
{
Computer a = (Computer)c;
if (this.cost == a.cost)
return 0;
else if (this.cost > a.cost)
return 1;
else
return -1;
}
0处的指数大于1处的指数,但只是为了澄清我将包括relvant公式:
cost = 150 + 6.50 * super.ram + 0.15 * super.hdd + 0.48 * super.vRam;
桌面(PROCESSOR,TYPE,RAM,VRAM,HDD SPACE):这就是参数的含义。
答案 0 :(得分:4)
行
computerSizes[i] = computerSizes[i+1];
computerSizes[i+1] = computerSizes[i];
不要做你期望的事。它首先将computerSizes[i+1]
的值分配给computerSizes[i]
。那一刻,两者是平等的。然后,您将computerSizes[i]
的值分配给computerSizes[i+1]
。最后,两者都是平等的。
要交换值,请使用时间变量:
Comparable temp = computerSizes[i];
computerSizes[i] = computerSizes[i+1];
computerSizes[i+1] = temp;
答案 1 :(得分:1)
使用Temp Comparable进行SWAP
Comparable tempComparable;
if(computerSizes[i].compareTo(computerSizes[i+1]) == 1){
tempCoparable = computerSizes[i];
computerSizes[i] = computerSizes[i+1];
computerSizes[i+1] = tempComparable;
}//end if
答案 2 :(得分:1)
让我们考虑一个数组:new int[3]{ 1, 2, 3 };
你在做的是:
a[i] = a[i+1];
a[i+1] = a[i];
(let i = 0):
1. {1,2,3}
2. {2,2,3} |a[0] i.e. 1 gets replaced by 2
3. {2,2,3} |a[1] i.e. 2 gets replaced by 2 (though it must be replaced by 1)
所以,必须有办法保留一个临时变量。 让我们考虑以下几点:
Computer temp = computerSizes[i];
computerSizes[i] = computerSizes[i+1];
computerSizes[i+1] = temp;
这将提供所需的结果。
答案 3 :(得分:0)
正如各种答案所说,你的交换代码不起作用,因为你没有中间变量
myarray[i] = myarray[i+1]; // both i and i+1 now refer to the same object
myarray[i+1] = myarray[i]; // so this line has no effect
如果您的目标是对对象进行排序,则可以通过提供比较器对象Arrays.sort()
来执行此操作 - 请参阅documentation。
答案 4 :(得分:0)
交换代码不正确。它应该是
if(computerSizes[i].compareTo(computerSizes[i+1]) == 1){
Computer temp = computerSizes[i]
computerSizes[i] = computerSizes[i+1];
computerSizes[i+1] = temp ;
}//end if