简体   繁体   English

Java的String类中length()函数的复杂性是什么?

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

Is it O(n) or O(1) (By saving length in a private variable during string allocation to the object). 是O(n)还是O(1)(通过在对象的字符串分配期间保存私有变量的长度)。

if it is O(n), does it mean that the complexity of following code is O(n^2)? 如果它是O(n),它是否意味着下面代码的复杂性是O(n ^ 2)?

for(int i=0; i<s.length()-1;i++){
    //some code here!
}

It is O(1) as the length is already known to String instance. 它是O(1)因为String实例已知长度。

From JDK 1.6 it is visible. 从JDK 1.6可以看出它。

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 . 重要的是要理解为什么他们可以缓存count的值并继续使用相同的count值。 The reason lies in a great decision they took when designing String , its Immutability. 原因在于他们在设计String时所做出的重大决定,即其不变性。

In Java any String is backed up by an final array. 在Java中,任何String都由final数组备份。 So it is simple to just return the array length. 因此返回数组长度很简单。 So it is O(1) complexity. 所以它是O(1)复杂性。 And if you think in your code 如果你在你的代码中思考

for(int i=0; i<s.length()-1;i++){
    //some code here!
}

s.length() is called for every iteration then you are not right. 每次迭代都会调用s.length() ,那么你就不对了。 Modern compiler optimizes this type of call and changes s.length() to constant number(ie the length of the String instance). 现代编译器优化此类调用并将s.length()更改为常量数(即String实例的长度)。

The complexity is O(1) Since String class have the length as a field . 复杂度为O(1)因为String类的长度为field It's not O(n^2). 它不是O(n ^ 2)。

String内部维护一个字符数组数组长度是数组对象的属性 ,因此O(1)作为其简单的属性读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM