[英]Java two equal Strings are not equal
I have the following problem: I have a String that I read from a MySQL Database (with the JDBC driver) and have to compare it with another String that I receive over TCP with a BufferedReader
. 我有以下问题:我有一个从MySQL数据库(使用JDBC驱动程序)读取的字符串,并且必须将其与通过
BufferedReader
通过TCP接收的另一个字符串进行比较。 When I use String.equals
, false is returned even if the Strings are exactly equal, I even printed both Strings to the console to make sure there aren't any typos or null objects. 当我使用
String.equals
,即使字符串完全相等也返回false,我什至将两个字符串都打印到控制台以确保没有任何错字或空对象。 String.compareTo
returns a negative number around -100. String.compareTo
返回-100附近的负数。
I am really confused here and have no concrete idea how to fix that. 我真的很困惑,不知道如何解决。 Maybe it's related to the database's encoding (UTF-8)?
也许与数据库的编码(UTF-8)有关?
As requested, here is my code snippet: 根据要求,这是我的代码段:
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;
}
And the console output is: 控制台输出为:
*TDM1* -84 *TDM1*
Thanks in advance! 提前致谢! Captain
队长
So I rebooted the entire system and retried. 因此,我重新启动了整个系统,然后重试。 Everything works now as expected.
现在一切正常。 I can't explain this to myself because I restarted the JVM multiple times and nothing happened, and a system reboot shouldn't affect a Java program like this.
我无法自己解释这一点,因为我多次重新启动了JVM,但没有任何反应,并且系统重新启动不应影响这样的Java程序。
I am sorry for everyone's time I wasted, but I really appreciate your quick help anyways. 很抱歉浪费我每个人的时间,但是无论如何,我非常感谢您的快速帮助。
EDIT : I use the trim
method from String
now. 编辑 :我现在使用
String
的trim
方法。 This method cuts off any leading null characters to prevent issues like this one. 此方法会切断所有前导的空字符,以防止出现此类问题。 I hope this will be helpful for someone who has the same problem!
希望对遇到同样问题的人有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.