All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.java.S1155.html Maven / Gradle / Ivy

The newest version!

Why is this an issue?

When you call isEmpty(), it clearly communicates the code’s intention, which is to check if the collection is empty. Using size() == 0 for this purpose is less direct and makes the code slightly more complex.

Moreover, depending on the implementation, the size() method can have a time complexity of O(n) where n is the number of elements in the collection. On the other hand, isEmpty() simply checks if there is at least one element in the collection, which is a constant time operation, O(1).

public class MyClass {
  public void doSomething(Collection<String> myCollection) {
    if (myCollection.size() == 0) { // Noncompliant
      doSomethingElse();
    }
  }
}

Prefer using isEmpty() to test for emptiness over size().

public class MyClass {
  public void doSomething(Collection<String> myCollection) {
    if (myCollection.isEmpty()) {
      doSomethingElse();
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy