gpt4 book ai didi

java - 使用 == 而不是 equals 来比较 Java 中的不可变对象(immutable对象)是否可以

转载 作者:搜寻专家 更新时间:2023-10-31 08:08:30 24 4
gpt4 key购买 nike

考虑调用静态工厂方法 valueOf 的两个 Integer 类型的引用,如下所示:-

    Integer a = Integer.valueOf("10"); 
Integer b = Integer.valueOf("10");

考虑到 Integer 是不可变的,是否可以使用 == 而不是使用 equals 方法来比较 a 和 b。我猜测 valueOf 方法确保只创建一个值为 10 的 Integer 实例,并且为每个创建的值为 10 的 Integer 返回对该实例的引用。

一般来说,通过使用 == 而不是 equals 来比较通过调用同一个静态工厂方法创建的不可变类的两个引用是否可以?

编辑:Integer 类仅用作示例。我知道如果使用 == 比较 127 以内的整数将返回 true。我需要知道的是,当我创建自己的不可变类时,比如 MyImmutable 和方法 create() 将确保不会创建重复的 MyImmutable 对象,如果我比较使用 create 方法创建的 2 个 MyImmutable 引用是否可以使用 == 而不是等于。

最佳答案

不,这通常不安全。 == 运算符比较引用,而不是值。

使用 == 恰好适用于 -128 到 127 之间的整数,但不适用于其他整数。以下代码演示了 == 并不总是有效:

Integer a = Integer.valueOf(10); 
Integer b = Integer.valueOf(10);
System.out.println(a == b);

true

Integer c = Integer.valueOf(1000);
Integer d = Integer.valueOf(1000);
System.out.println(c == d);

false

在线查看它:ideone

此行为的解释在于 Integer.valueOf 的实现:

public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}

source

也不是因为标准要求小输入(-128 到 127)的装箱整数给出具有相同引用的对象。

5.1.7 Boxing Conversion

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

但是,该标准不对超出此范围的整数做出此类保证。


In general, is it ok to compare two references of an immutable class that are created using a call to the same static factory method by using == instead of equals?

如上所示,一般情况下是行不通的。但是,如果您确保具有相同值的两个不可变对象(immutable对象)始终具有相同的引用,那么是的,它可以工作。但是,您必须仔细遵守一些规则:

  • 构造函数不能公开。
  • 您通过静态方法创建的每个对象都必须缓存。
  • 每次要求您创建一个对象时,您必须首先检查缓存,看看您是否已经创建了一个具有相同值的对象。

关于java - 使用 == 而不是 equals 来比较 Java 中的不可变对象(immutable对象)是否可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10970823/

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