Difference between size and length methods?

前端 未结 6 649
北海茫月
北海茫月 2020-12-12 14:46

What is the difference between .size() and .length ? Is .size() only for arraylists and .length only for arrays?

6条回答
  •  佛祖请我去吃肉
    2020-12-12 14:51

    size() is a method specified in java.util.Collection, which is then inherited by every data structure in the standard library. length is a field on any array (arrays are objects, you just don't see the class normally), and length() is a method on java.lang.String, which is just a thin wrapper on a char[] anyway.

    Perhaps by design, Strings are immutable, and all of the top-level Collection subclasses are mutable. So where you see "length" you know that's constant, and where you see "size" it isn't.

提交回复
热议问题