[英]Java Character Equality on Special Character
I was trying to get the equality of 'ü' == 'ü'.我试图获得 'ü' == 'ü' 的相等性。 This returns true if I write like this (in sout).
如果我这样写(在sout中),这将返回true。 But in my code:
但在我的代码中:
static Character[] charset = {'ü'};
public static void main(String[] args) {
ArrayList<Character> mustContain = new ArrayList<>();
mustContain.add('ü');
ArrayList<Character> removal = new ArrayList<>();
for (int i = 0; i < charset.length; i++) {
for (int j = 0; j < mustContain.size(); j++) {
if(charset[i] == 'ü' && mustContain.get(j) == 'ü') {
System.out.println(charset[i] instanceof Character);
System.out.println(mustContain.get(j) instanceof Character);
}
if(charset[i] == (mustContain.get(j))){
System.out.println("added");
removal.add(mustContain.get(j));
}
}
}
System.out.println(Arrays.toString(removal.toArray()));
}
This is the result:这是结果:
true
true
[]
What I hope to get was:我希望得到的是:
true
true
added
[ü]
I can only get this equality as true with charset[i].equals(mustContain.get(j))我只能用charset[i].equals(mustContain.get(j))
But for the Character 'a' everything is okay with the code, both == and .equals() returns true.但是对于字符 'a' 代码一切正常,== 和 .equals() 都返回 true。 For 'ü' only .equals() works.
对于 'ü' 只有 .equals() 有效。 I really wonder why equals works and == not?
我真的想知道为什么 equals 有效而 == 无效?
My answer to this behavior is that ==
performs reference comparison.我对这种行为的回答是
==
执行引用比较。
Try to set up a break point at the line尝试在该行设置断点
if(charset[i] == (mustContain.get(j))
By inspecting charset[i]
and mustContain.get(j)
You will see that the reference is different for the case of the special character, which gives the result: false.通过检查
charset[i]
和mustContain.get(j)
您将看到对于特殊字符的情况,引用是不同的,这给出了结果:false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.