Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.length() vs .getText().length() vs .getText().toString().length()

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()?

like image 570
hofs Avatar asked Apr 02 '16 15:04

hofs


2 Answers

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

like image 84
CommonsWare Avatar answered Oct 15 '22 18:10

CommonsWare


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()

like image 43
TacoEater Avatar answered Oct 15 '22 16:10

TacoEater