Java 有人能给我解释一下这个逻辑吗?看来两者是相等的
有人能给我解释一下为什么a和b都相等,而x和y不都相等,但它们有相同的值Java 有人能给我解释一下这个逻辑吗?看来两者是相等的,java,Java,有人能给我解释一下为什么a和b都相等,而x和y不都相等,但它们有相同的值 Integer a = 40;`// integer a Integer b =40; // integer b Integer x = 400; // why x and y are not equal Integer y = 400; // how is that possible if (a==b){ //first condition System.out.println("a=b"); //if
Integer a = 40;`// integer a
Integer b =40; // integer b
Integer x = 400; // why x and y are not equal
Integer y = 400; // how is that possible
if (a==b){ //first condition
System.out.println("a=b"); //if true print
}else {
System.out.println("a!=b"); // if not true
}
if(x==y){ // second condition
System.out.println("x=y"); // if true print
}else{
System.out.println("x!y"); // if not true print
}
将对象与==进行比较是一个错误(或者实际上是一个糟糕的做法),因为大多数对象都会覆盖
compareTo()
,显然整数也不例外。您不应该使用=
来比较对象。使用x.intValue()
,将它们与.equals()
进行比较,或者首先将它们创建为基元类型int
。或者在任何情况下,将它们创建为equals()