为什么 String equals() 返回 false(涉及自定义比较器)?
我构建了一个非常简单的自定义比较器,将其与 TreeSet 一起使用,以便按 TreeSet 中的长度对字符串进行排序。
即使两个字符串 s1 和 s2 包含相同的值,我也无法找到 (s1.equals(s2))
返回 false 的原因。
Eclipse“变量视图”显示两个字符串中的字母相同,但“id”不同,我想这就是 equals 返回 False 的原因。 顺便问一下,id=" "
代表什么?它是某种指向 String 对象数据的指针吗?
public class MyComparator implements Comparator<String> {
public int compare(String s1, String s2) {
if(s1.length()<s2.length()) return -1;
else if (s1.length()>s2.length()) return 1;
return 0;
else if (s1.equals(s2)) return 0; //?? ALWAYS RETURNS FALSE
else if (s1.toString().equals(s2.toString()))//SAME PROBLEM HERE (test)
else return -1;
}
public boolean equals(String s) {
if (this.equals(s)) return true;
else return false;
}
}
现在,我在这里使用这个自定义比较器:
combinations = new TreeSet<String>(new MyComparator());
我用多个字符串填充组合,这些字符串是使用 substring()
方法构建的。
由于前面提到的问题,组合包含重复项。
当我为此 TreeSet 设置“没有自定义比较器”时,不再有重复项(这就是我想要的),但它按字母顺序排序,这是正常的,但不是我的目的。
I built a very simple custom Comparator, that I use with a TreeSet in order to sort Strings by length in that TreeSet.
I'm having trouble finding the reason why (s1.equals(s2))
returns false even when the two strings s1 and s2 contain the same value.
Eclipse "variables view" shows the letters are the same in both strings, but the "id" is different, I guess that's why equals returns False.
By the way what is that id=" "
representing? Is it some kind of pointer to the String object data?
public class MyComparator implements Comparator<String> {
public int compare(String s1, String s2) {
if(s1.length()<s2.length()) return -1;
else if (s1.length()>s2.length()) return 1;
return 0;
else if (s1.equals(s2)) return 0; //?? ALWAYS RETURNS FALSE
else if (s1.toString().equals(s2.toString()))//SAME PROBLEM HERE (test)
else return -1;
}
public boolean equals(String s) {
if (this.equals(s)) return true;
else return false;
}
}
Now here is where I use this custom Comparator:
combinations = new TreeSet<String>(new MyComparator());
I fill combinations with several Strings, built with the substring()
method.
Because of the previously mentioned problem, combinations contains duplicates.
When I set NO custom Comparator for this TreeSet, there is no duplicate any more (that's what I want) but it is sorted alphabetically which is normal but not my purpose.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想要做的是按长度排序但丢弃重复项,则以下操作应该可行。
输出:
[, 1, H, He, Hel, Hell, Hello, hello, Hello , long, Hello W, Hello Wo, Hello Wor, Hello Worl, Hello World, 477727357235]
If what you're trying to do is sort by length but discard duplicates, the following should work.
Output:
[, 1, H, He, Hel, Hell, Hello, hello, Hello , longer, Hello W, Hello Wo, Hello Wor, Hello Worl, Hello World, 477727357235]