I took up Core Core in Java and, in particular, its substring()
method. As I understand it, the String
object itself is not an array of char
's, but the substring
method operates with an array of charms created from our String
. Can you please tell the scheme of when exactly this array is created? Where is it stored? Or, if possible, please give a link to the article (I did not find anything on the network myself).
- > I firmly took up the issue of Core basics in Java Oh, and you have a boring job. It would be better if you specifically said the goal. There, people have written and read too many years: The array is defined like this: / ** The value is used for character storage. * / private final char value []; And this is how it is created: this.value = Arrays.copyOf (value, size); - Vladislav Pyatkov
2 answers
By itself, a String
is a class in which the value lies in the form of an array of char
.
Source: http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/src/share/classes/java/lang/String.java
In general, of course it is not good to climb into the guts of realization, but it will do for self-education.
- 2just for self-education to see the implementation inside it. After that, the feeling of “magic” disappears, the work of the compiler / language is better understood, the quality of the code improves. - KoVadim
- @KoVadim, I just meant that it’s not good at all to get involved in internal implementation, for tomorrow everything can change. And to look good code samples, yes, it is necessary. - delphist007 2:51 pm
Is it otherwise a string is a "wrapper" around an array of characters. When a string is created, the offset field is set to 0, and the array of characters is filled with values. When calling the substring method (as well as Pattern.split), it wasn’t really necessary to copy the data, it was enough to give an object that had the offset field changed. This speeds up the runtime, but leaves room for leaks.
But now all of the above is no longer the case. The offset field is no longer used and the lines between the objects are not “shuffled”, but fair copying occurs. Discussion of changes can be found here http://www.rsdn.ru/forum/java/4988346
The latest version of OpenJDK can be found here http://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/lang/String.java