hofs
hofs

Reputation: 469

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

Upvotes: 19

Views: 7742

Answers (3)

TacoEater
TacoEater

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

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6856

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

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

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

Upvotes: 5

CommonsWare
CommonsWare

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

Related Questions