Reputation: 161
I've done quite a bit of string comparisons in java in the past, but this time it doesn't seem to work.
I'm aware of the fact, that you have to use the .equals()
function in order to compare strings in java.
In my attempt to figure out what's wrong, I wrote the following code snippet:
Log.e("testLogic", String.valueOf(taken.getText().toString().trim().equals('1')));
Log.e("testValue", taken.getText().toString().trim());
producing the following result:
E/testLogic﹕ false
E/testValue﹕ 1
E/testLogic﹕ false
E/testValue﹕ 1
E/testLogic﹕ false
E/testValue﹕ 0
This seems rather strange, since the two first 'testLogic' logs should produce true.
The code is used in a custom list adapter if it means anything.
/Mikkel
Upvotes: 0
Views: 196
Reputation: 11163
The .equals()
comes from the Object
class. Each class inherit it from the Object
class. String
class also inherited it from the Object
class and override it like this -
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
And String
has not any overloaded version of equals
method for char
. You can see if String
's .equals()
method takes any object but it returns false
when it is any type rather than String
. It only returns true
if the provided parameter is of type String
and is meaningfully equals. So you have to write -
Log.e("testLogic",String.valueOf(taken.getText().toString().trim().equals("1")));
instead of -
Log.e("testLogic", String.valueOf(taken.getText().toString().trim().equals('1')));
Upvotes: 0
Reputation: 13199
It is because you are not comparing 2 Strings
. You have to put it like this:
Log.e("testLogic", String.valueOf(taken.getText().toString().trim().equals("1")));
because .equals()
function needs two Strings
. Supposing that s1
and s2
are Strings
, you should do:
s1.equals(s2);
I expect it will be helpful for you!
Upvotes: 2