For example in the code below a
and b
and c
are equal.
EditText editText;
editText = (EditText) findViewById(R.id.edttxt);
editText.setText("1234");
int a, b, c;
a = editText.length();
b = editText.getText().length();
c = editText.getText().toString().length();
What is difference between length()
and getText().length()
and getText().toString().length()
?
.length()
and getText().length()
are identical in their current implementation.
.getText().toString().length()
will convert the CharSequence
into a plain String
, then compute its length. I would expect that to return the same value as the other two in many cases. However, if the CharSequence
is something like a SpannedString
, I cannot rule out the possibility that there is some type of formatting span (e.g., ImageSpan
) that affects length calculations.
It's a matter of performance.
length
will do exactly the same as getText
and length
it just saves you from typing getText()
.
From class TextView
which EditText
extends:
public CharSequence getText() {
return mText;
}
/**
* Returns the length, in characters, of the text managed by this TextView
*/
public int length() {
return mText.length();
}
As to toString
, it's the same, however, any conversion you make (CharSequence
=> String
) will cost you a tiny bit in performance (so little you'll probably not notice it).
Also, when you convert stuff you have to look out for null pointer exceptions, maybe not in this instance but generally speaking.
To answer the question, just use length()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With