gpt4 book ai didi

java - 为什么避免 boolean 实例化是个好主意?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:05:24 26 4
gpt4 key购买 nike

PMD 警告我避免 boolean 实例化(出于效率原因)。我有这样的东西

Boolean variable = new Boolean(somestringIGotRepresentingABoolean);

我应该用这个

Boolean variable = Boolean.valueOf(somestringIGotRepresentingABoolean);

为什么这样更好?

最佳答案

原因是 new Boolean 总是返回一个新的实例。由于 boolean 实例是不可变的,因此拥有超过 2 个实例是没有意义的。一个为假,一个为真。

试试这个,你会看到

Boolean boolean1 = new Boolean("true");
Boolean boolean2 = new Boolean("true");
Boolean boolean3 = new Boolean("true");

System.out.println(System.identityHashCode(boolean1));
System.out.println(System.identityHashCode(boolean2));
System.out.println(System.identityHashCode(boolean3));

Boolean valueOf1 = Boolean.valueOf("true");
Boolean valueOf2 = Boolean.valueOf("true");

System.out.println(System.identityHashCode(valueOf1));
System.out.println(System.identityHashCode(valueOf2));

关于java - 为什么避免 boolean 实例化是个好主意?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24797155/

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