Reputation: 469
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()
?
Upvotes: 19
Views: 7742
Reputation: 2278
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()
Upvotes: 8
Reputation: 6856
length()
:- length()
function is an inherited method for EditView
which is getting inherited by TextView
that returns the length, in characters, of the text managed by this EditView
. So, it will return the length of text that user put into the EditView
Contorl.
getText().length()
:- here in this statement length()
function does not belongs to EditView
class . In actual this length()
Function belong to CharSequence
class because getText()
return a CharSequence
object. So, again this function length()
will return the number of characters in this sequence.
.getText().toString().length()
:- here toString()
method Convert the CharSequence
Object into a plain immutable String
Object. So, here length()
function belongs to String
class which also return the length of String
objectUpvotes: 5
Reputation: 1007286
.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.
Upvotes: 21