【问题标题】:Integer comparison, 10 and 128 [duplicate]整数比较,10 和 128 [重复]
【发布时间】:2014-12-14 05:20:13
【问题描述】:

我发现了一个有趣的事实,但我不知道它是怎么发生的。

Integer x = 10;
Integer y = 10;
System.out.print(x==y);    // true
Integer x = 128;
Integer y = 128;
System.out.print(x==y);    // false

【问题讨论】:

  • 这里需要使用.equals()。见this question==.equals() 的行为不同。

标签: java integer


【解决方案1】:

Integer 比较使用 == 仅适用于 -128 和 127 之间的数字。

因为IntegerObject,所以使用equals,它将适用于所有值。

【讨论】:

  • 实际上它适用于您要测试对象身份的所有整数。当您使用 valueOf() 或通过装箱创建 Integer 对象时,您将获得 -128…127 范围内的 Integer 的缓存单例(但这是可配置的)stackoverflow.com/a/15052272
猜你喜欢
  • 1970-01-01
  • 2017-07-09
  • 2012-09-14
  • 2016-03-19
  • 2021-08-21
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 2013-05-28
相关资源
最近更新 更多