我有以下问题:我有一个字符串,我从MySQL数据库(使用JDBC驱动程序)读取,并且必须将它与通过TCP接收的另一个字符串(BufferedReader
)进行比较。当我使用String.equals
时,即使字符串完全相等,也会返回false,我甚至会将两个字符串都打印到控制台,以确保没有任何拼写错误或null对象。 String.compareTo
返回-100左右的负数。Java两个相等的字符串不相等
我真的很困惑,并没有具体的想法如何解决这个问题。也许它与数据库的编码(UTF-8)有关?
按照要求,这里是我的代码片段:
public TeleportSign getTeleportSign(String target) {
// I used a HashMap, but I switched to an ArrayList in order to be able
// to compare the Strings directly.
//return signs.get(target);
for(TeleportSign s : signsList) {
// I am printing the Strings here. I even put stars to the left
// and the right of the String to make sure there are no
// spaces or new lines. s.getTarget() returns the String from the DB,
// target is the String sent over TCP.
System.out.println("*" + s.getTarget() + "* " +
String.valueOf(s.getTarget().compareTo(target))
+ " *" + target + "*");
if(s.getTarget().compareTo(target) == 0)
return s;
}
return null;
}
和控制台输出为:提前
*TDM1* -84 *TDM1*
谢谢! 队长
什么是字符串值请添加代码片段 –
什么是两个字符串值? – Bathsheba
打印出两个字符串中每个字符的数字字符值。你会注意到他们仅仅*看起来就像未经训练的眼睛! – Kayaman