Java中是否有类似Python的关键字';s";“是”吗;?
Java中有类似“Is”的东西吗?根据内存位置计算为真的东西Java中是否有类似Python的关键字';s";“是”吗;?,java,python,keyword,Java,Python,Keyword,Java中有类似“Is”的东西吗?根据内存位置计算为真的东西 a = 1 b = a print(id(a)) print(id(b)) # if a is b condition will evaluate to true # the above print statement gives the same memory ID. In my case: 14374435888 # above assignment b = a is not the same as below a = 1 b
a = 1
b = a
print(id(a))
print(id(b))
# if a is b condition will evaluate to true
# the above print statement gives the same memory ID. In my case: 14374435888
# above assignment b = a is not the same as below
a = 1
b = 1
假设您有三个字符串:
String a = "first";
String b = "second";
String c = a;
// false, because they're in different memory locations
System.out.println(a == b);
// true, because they point to the same location in memory
System.out.println(a == c);
在Java中,
=
相当于is
。在Python的是
(你也不应该这样想Java的=
)<如果其参数是相同的对象,则code>is给出True
。从记忆的角度来思考它是在错误的抽象层,如果对象在内存中移动或新对象在旧对象使用的空间中分配,则会产生不必要的混淆。根据相同的内存位置思考is
,就像通过两个人是否坐在同一张椅子上思考两个人是否是同一个人。这可能也是错误的吗因为它们不是同一根弦?只是想知道。将“second”替换为“first”,然后观察接下来会发生什么。@Stultuske如果我没记错的话,Java优化器利用字符串的不变性,允许两个变量引用同一个字符串。在某些特殊情况下,优化器不适用(即,如果使用stringA==stringB,当它们具有相同的字符时,将得到false)。不能依赖“==”运算符来比较字符串。相反,您应该使用String.equals方法。您的调用不正确。如果使用字符串b=“first”;a==b将返回true,因为使用了相同的池。如果你想强制一个新的,你需要使用字符串b=newstring(“first”);谢谢你的洞察力,你说的“池”是什么意思?字符串池