What is complexity of length() function in String class of Java?

后端 未结 4 1826
栀梦
栀梦 2021-02-20 07:53

Is it O(n) or O(1) (By saving length in a private variable during string allocation to the object).

if it is O(n), does it mean that the complexity of following code is

4条回答
  •  盖世英雄少女心
    2021-02-20 08:23

    It is O(1) as the length is already known to String instance.

    From JDK 1.6 it is visible.

    public int length() {
        return count;
    }
    

    Update

    It is important to understand why they can cache the value of count and keep using same value for count. The reason lies in a great decision they took when designing String, its Immutability.

提交回复
热议问题