Java implements a simple character generator code example
- 2020-04-01 03:54:25
- OfStack
Creates a successful string object whose length is fixed and whose content cannot be modified or edited. While "+" can be used to add new characters or strings, "+" generates a new String instance and creates a new String object in memory. If you make changes to the string repeatedly, you will greatly increase the overhead. J2SE adds the variable character sequence string-builder class from 5.0, greatly increasing the efficiency of adding strings frequently. Let's look at a simple example.
public class Jerque {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "";
long startTime1 = System.currentTimeMillis();
for (int i =0; i<10000; i++)
{
str = str +i;
}
long endTime1 = System.currentTimeMillis();
long time1 = endTime1 - startTime1;
System.out.println(" string 1 Elapsed time :"+ time1);
StringBuilder builder = new StringBuilder("");
long startTime2 = System.currentTimeMillis();
for (int i=0;i<10000;i++)
{
builder.append(i);
}
long endTime2 = System.currentTimeMillis();
long time2 = endTime2 - startTime2;
System.out.println(" string 2 Elapsed time :" + time2);
}
}
String 1 elapsed time :1210& PI;
String 2 consumes time :3& PI;
Conclusion:
1. The String-Builder class, which comes with JAVA, undoubtedly greatly improves the efficiency.
2. The usual methods of doing this are :
A. Append (content) method
B. Insert (int offset,arg) method & offset;
StringBuilder b = new StringBuilder("Hello");
B.i nsert (5, "World!" );
System. The out. Println (b.t ostring ());
C. Delete (int start,int end) method
StringBuilder d = new StringBuilder("StringBuilder");
D.d elete (5, 10);
System. The out. Println (" which oString () ");