-3

I'm wondering why there's an isEmpty() method in Java's List interface since there's a size() method. And when used as a loop guard, which one is better, list.isEmpty() or list.size == 0?

2 Answers2

0

I'd say they are the same :

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

 public int size() {
     return size;
 }
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Most implementations of List.isEmpty() actually tests for List.size() == 0. That being said the JVM can easily optimize this method and it is best to use List.isEmpty() over List.size() == 0 for clarity purposes.

hlt
  • 6,219
  • 3
  • 23
  • 43
Smith_61
  • 2,078
  • 12
  • 12