In C++ String is mutable , So there won't be any Problem.
But in Java String is immutable which creates problem and we have to resolve it .
So as String is immutable , If you want to change to change the String you have to create a new String even if you want to change one character .
So if we have to do String Concatenation in Java using '+' . It will take O(N*N) time .
String Concatenation is Slow in Java compared to C++ Which is not noticeable .
In Java Concatenation happens by first allocating enough space for new string and copy the contents from old string and append to the new String.
Time Complexity for a String of length 10 and n = 10000 is :
10+10* 2 +10 * 3 + ...... + 10 * n
= 10 * n * (n+1) / 2
Which will be O(N*N).
Example :
package com.techyield.operationsinarray;
public class StringConcatenation {
public static void main(String[] args) {
String s = "";
int n = 200000;
for(int i =0 ; i< n ;i++) {
s += "hello";
}
}
}
So you want to make String Immutable to Mutable :
Check here : https://techyield.blogspot.com/2019/06/string-immutable-to-mutable-java.html
No comments:
Post a Comment