Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

CompareTo method in java acting weird

I have an issue with the compareTo method in java, this is the code:

for(int i = 0; i < btFolder.size(); i++) {

        String g = btFolder.get(i).toString();

        String[] subf = g.split(splitchar);

        String s = subf[subf.length-1].toUpperCase();

        if(s.compareTo(bt.toUpperCase()) == 0) {
            return g; 
        }
    }
    return null; //not found!

this will not jump into the if-statement, it should because the s and bt variables are equal, I know because I've done my homework and debugged it. Just to figure out what the compareTo method return I wrote this piece of code:

        String g = btFolder.get(i).toString();

        String[] subf = g.split(splitchar);

        String s = subf[subf.length-1].toUpperCase();

        String btUp = bt.toUpperCase();

        int theSame = s.compareTo(btUp);

        if(theSame == 0) {
           putSharedPrefs("pathToBt", g); 
        }
        return null; 

The variable theSame is 0, which means that s and btUp is equal. And still, the if-statement is never executed!

Why is this happening? Any good solutions to this?

EDIT

I've tried this too:

boolean equals = s.equalsIgnoreCase(bt);

        if(equals) {
            return g; 
        }

The boolean is true, but never excutes the if-statement, I should also mentioned that this is done inside a thread, but that should not cause any problem?

Upvotes: 0

Views: 153

Answers (2)

Bharat Sinha
Bharat Sinha

Reputation: 14363

In this snippet

if(theSame == 0) {
       putSharedPrefs("pathToBt", g); 
}

if you can debug and check that theSame is 0 then please put a sysout and see whether its printed or not.

Since you are quite sure that if is not being executed; it seems the case that the code you are debugging and the code being executed are not same. This sometimes happens in eclipse when the build is not deployed and you are debugging new source with old executable.

Upvotes: 2

ramsinb
ramsinb

Reputation: 2005

Why not just do:

if (s.equalsIgnoreCase(bt) {
    return g; 
}

I guess you can use compareTo however it does other things too...

Upvotes: 0

Related Questions