equals与内存比较问题

huangapple go评论68阅读模式
英文:

equals versus memory comparision issue

问题

public static void main(String[] args) {
  Long l = 500L;
  Long l1 = 500L;
  System.out.println(l == l1);
  User u = new User();
  u.setL(500L);
  User u1 = new User();
  u1.setL(500L);
  System.out.println(u.getL() == u1.getL());
}

The output of the above program comes as false,true. Why it was making a different output.

public class User {

	private long l;

	public long getL() {
		return l;
	}

	public void setL(long l) {
		this.l = l;
	}

}

The above definition is for the User class.

英文:
public static void main(String[] args) {
  Long l = 500L;
  Long l1 = 500L;
  System.out.println(l == l1);
  User u = new User();
  u.setL(500L);
  User u1 = new User();
  u1.setL(500L);
  System.out.println(u.getL() == u1.getL());
}

The output of the above program comes as false,true. Why it was making difference output.

public class User {

	private long l;

	public long getL() {
		return l;
	}

	public void setL(long l) {
		this.l = l;
	}

}

The Above definition is for user class

答案1

得分: 6

Long不是原始数据类型,而是一个将long包装为对象的类。
因此,您不能使用==运算符来比较这两个对象,它将始终返回false。
您需要使用equals()方法。

英文:

Long is not a primitive data type but a class to wrap the long into an object.
So you cannot compare those 2 objects using == operator, it will always return false.
You need to use equals().

答案2

得分: 1

自从Long作为包装类,==会比较引用,就像两个变量是否指向完全相同的对象(内存中的同一位置)。要比较对象的内部内容,您需要使用equals()方法。但是,如果User.gerL()返回原始的long类型,那就是另一回事了。对于原始数据类型,==会比较存储在这些原始类型中的内部值。这就是为什么第二次比较返回true。

英文:

Since Long is a wrapper class == compares references like if two variable point to the exactly same object (same location in memory). To compare internals of the objects you need to use equals(). But if User.gerL() returns primitive long that is another story. For primitive types == compares internal values stored in those primitives. That is why second comparison returns true.

huangapple
  • 本文由 发表于 2020年10月19日 10:47:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64420483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定