Difference between isEmpty and equals ("")

Possible duplicate:
Should I use string.isEmpty () or "" .equals (string)?

I am wondering what is the difference between isEmpty and equals ("")? They seem the same to me.

+3
source share
5 answers

java.lang.String.isEmpty() is faster because it simply compares the length of the string that is stored in the String object with zero:

1286       public boolean isEmpty() {
1287           return 0 == count;
1288       }

Usage equals("")performs actual string comparisons, which should be slower, although the JVM can offset some of its cost. In most implementations, it also includes length checking:

854       public boolean equals(Object object) {
855           if (object == this) {
856               return true;
857           }
858           if (object instanceof String) {
859               String s = (String) object;
860               int hash = hashCode;  // Single read on hashCodes as they may change
861               int shash = s.hashCode;
862               if (count != s.count || (hash != shash && hash != 0 && shash != 0)) {
863                   return false;
864               }
865               for (int i = 0; i < count; ++i) {
866                   if (value[offset + i] != s.value[s.offset + i]) {
867                       return false;
868                   }
869               }
870               return true;
871           }
872           return false;
873       }

Note. Both fragments are taken from this java.lang.String implementation .

EDIT:

JVM equals("") , , - isEmpty(). . isEmpty() JVM .

, isEmpty() , , .

, null, , , :

if ("".equals(string)) ...
+8

, isEmpty():

  • equals("") ( , ), ,
  • isEmpty() , ( count). .

, null, apache commons-lang StringUtils.isEmpty(..)

+7

( , ). isEmpty() , , . , . .

+1
0

OpenJDK isEmpty:

public boolean isEmpty() {
    return count == 0;
}

, . , equals("") , , .

0

Source: https://habr.com/ru/post/1788862/


All Articles