I've been told that code such as:
for (int i = 0; i < x.length(); i++) { // blah }
is actually O(n^2) because of the repeated calls to x.length()
. Instead I should use:
int l = x.length(); for (int i = 0; i < l; i++) { // blah }
Is this true? Is string length stored as a private integer attribute of the String class? Or does String.length()
really walk the whole string just to determine its length?
The key difference between Java's length variable and Java's length() method is that the Java length variable describes the size of an array, while Java's length() method tells you how many characters a text String contains.
Java String length() Method The length() method returns the length of a specified string.
The Java String length() method is a method that is applicable for string objects. length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays. The length() method can also be used for StringBuilder and StringBuffer classes.
The complexity is O(1) Since String class have the length as a field .
No, the length of a java string is O(1) because java's string class stores the length as a field.
The advice you've received is true of C, amongst other languages, but not java. C's strlen walks the char array looking for the end-of-string character. Joel's talked about it on the podcast, but in the context of C.
Contrary to what has been said so far, there is no guarantee that String.length()
is a constant time operation in the number of characters contained in the string. Neither the javadocs for the String
class nor the Java Language Specification require String.length
to be a constant time operation.
However, in Sun's implementation String.length()
is a constant time operation. Ultimately, it's hard to imagine why any implementation would have a non-constant time implementation for this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With