Java 当n1等于n2时,如何使我的代码返回true?
我的问题和问题:1.当n1==n2==5并且我运行这个程序时,它显示:“n1等于n2?false”,这是有问题的,我如何修复它Java 当n1等于n2时,如何使我的代码返回true?,java,Java,我的问题和问题:1.当n1==n2==5并且我运行这个程序时,它显示:“n1等于n2?false”,这是有问题的,我如何修复它 1st part of the code class MyInteger { int value; public MyInteger(int value){ } public static int get(
1st part of the code
class MyInteger {
int value;
public MyInteger(int value){
}
public static int get(int value) {
return value;
}
public static char[] parseInt(char[]chars) {
//converting array of numeric numbers to int numbers
return MyInteger.parseInt(chars);
}
public void equals(int value) {
}
}
您尚未覆盖该方法。方法要求对象作为输入参数,而不是基元int
您的方法将不会在使用equals和hashCode的集合、映射和其他结构中使用。这只是另一种对象方法
你的对手是这样的:
@Override
public boolean equals(Object o) {
// self check
if (this == o)
return true;
// null check
if (o == null)
return false;
// [TIP] If you want to compare to an Integer, you can do it here
// type check and cast
if (getClass() != o.getClass())
return false;
MyInteger other = (MyInteger) o;
// field comparison
return this.value == other.value;
}
您还需要指定值:
public MyInteger(int value){
this.value = value;
}
没有它,所有值都将等于0,从而使它们彼此相等
现在输出为:
MyInteger n1 = new MyInteger(1);
MyInteger n2 = new MyInteger(2);
MyInteger n3 = new MyInteger(2);
System.out.println(n2.equals(n1)); // false
System.out.println(n2.equals(n3)); // true
重写
boolean equals(Object other)
method另外,更改当前正在调用自身的public static char[]parseInt(char[]chars)
方法。我已将上述代码添加到程序的第一部分,但该程序做出的反应仍然是错误的。运行该程序后,它会显示以下消息(n1=n2=4):n1等于n2?真的n1等于5?错误在您的示例中,您没有设置值。
MyInteger n1 = new MyInteger(1);
MyInteger n2 = new MyInteger(2);
MyInteger n3 = new MyInteger(2);
System.out.println(n2.equals(n1)); // false
System.out.println(n2.equals(n3)); // true