Java的String类中length()函数的复杂度是多少? [英] What is complexity of length() function in String class of Java?
本文介绍了Java的String类中length()函数的复杂度是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是 O(n) 还是 O(1)(通过在向对象分配字符串期间将长度保存在私有变量中).
Is it O(n) or O(1) (By saving length in a private variable during string allocation to the object).
如果是O(n),是不是意味着下面代码的复杂度是O(n^2)?
if it is O(n), does it mean that the complexity of following code is O(n^2)?
for(int i=0; i<s.length()-1;i++){
//some code here!
}
推荐答案
O(1)
因为String
实例的长度是已知的.
It is O(1)
as the length is already known to String
instance.
从 JDK 1.6 开始可见.
From JDK 1.6 it is visible.
public int length() {
return count;
}
<小时>
更新
了解为什么他们可以缓存 count
的值并继续为 count
使用相同的值很重要.原因在于他们在设计 String
时做出了一个伟大的决定,即它的不可变性.
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.
这篇关于Java的String类中length()函数的复杂度是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文