-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
  • 374,785
  • 51
  • 663
  • 734
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,001
  • 2
  • 22
  • 40
Smith_61
  • 2,050
  • 9
  • 12