gpt4 book ai didi

java - 在 Java 中比较两个整数对象

转载 作者:行者123 更新时间:2023-12-01 18:11:16 24 4
gpt4 key购买 nike

这不是一个重复的问题!我不是比较两个整数,而是比较一个整数和一个 int 值。此外,我询问人们对我正在做的事情的看法,而不是告诉我如何正确比较......

我只是想知道您对将 Integer 类型的对象与这样的 int 值进行比较有何看法:

final Integer i = null; //I'm setting it to null just to show that my test will not throw a NullPointerException, otherwise I could used a simple `int`
if (i == Integer.valueOf(3))
...

我发现这样做有用的是不需要检查我的对象是否为空。而且Integer.valueOf()缓存对象....

最佳答案

这是一个坏主意,因为它可能会给你错误的结果。

final Integer i = Integer.valueOf(Integer.MAX_VALUE);
System.out.println(i == Integer.valueOf(Integer.MAX_VALUE));

给你

我猜你尝试了一些小数字,他们给了你正确的结果。但是一旦您尝试的数字高于 127 或低于 -128,您的结果很可能是错误的

public static Integer valueOf(int i)

[...]This method will always cachevalues in the range -128 to 127, inclusive, and may cache other valuesoutside of this range.

Source

关于java - 在 Java 中比较两个整数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32823913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com