Java 如何将对象与另一个对象进行比较
我运行以下命令Java 如何将对象与另一个对象进行比较,java,Java,我运行以下命令 Choice choice1 = new Choice(0); Choice choice2 = new Choice(1); int result = choice1.compareWith(choice2); IO.outputln("Actual: " + result); 比较法 public int compareWith(Choice anotherChoice) { int result=0;
Choice choice1 = new Choice(0);
Choice choice2 = new Choice(1);
int result = choice1.compareWith(choice2);
IO.outputln("Actual: " + result);
比较法
public int compareWith(Choice anotherChoice)
{
int result=0;
if (anotherChoice==0||type==0)
result=1;
if (anotherChoice==1&&type==1)
result=-11;
}
程序说我不能将另一个选项(选项类)与整数进行比较。我该怎么做呢
if (anotherChoice==0||type==0)
由于另一个选择
是一个对象,您无法直接与0
进行比较。实际上应该检查该对象的字段。所以你的代码应该是
if (anotherChoice.type==0|| this.type==0)
其他条件也一样
另一个错误是没有从方法返回任何内容。你应该
public int compareWith(Choice anotherChoice)
{
int result=0;
if (anotherChoice==0||type==0)
result=1;
if (anotherChoice==1&&type==1)
result=-11;
return result;
}
您应该为此实施
Comparable
。在比较值时,还需要从选项中选择类型
值:
public class Choice implements Comparable<Choice>
{
@Override
public int compareTo(Choice that)
{
int result = 0;
if (anotherChoice.type == 0 || type == 0)
result = 1;
if (anotherChoice.type == 1 && type == 1)
result = -11; // should probably be -1
return result;
}
}
公共类选择实现了可比较的
{
@凌驾
公共整数比较(选择该选项)
{
int结果=0;
if(anotherChoice.type==0 | | type==0)
结果=1;
if(anotherChoice.type==1&&type==1)
result=-11;//可能应该是-1
返回结果;
}
}
如错误所述,另一个选项的类型为Choice
。我假设您想要比较实例变量类型
。所以它应该是另一个选择.type==this.type