简体   繁体   中英

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 . 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.compareTo returns a negative number around -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)?

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.

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. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM