This is a memo for yourself for studying
--About the difference between String and StringBuilder in the first place --About stringsbuilder equals
The conclusion is --StringBuilder is recommended when joining and flipping --If not, String may be more convenient & safe --Be careful about string match judgment with String and StringBuilder!
Recently, I am studying Java grammar using the AtCoder problem.
ABC146 F -Sugoroku It is a story that starts when I came across something called StringBuilder when I wanted to invert String when I came across.
You can easily understand this by looking at the link below. https://qiita.com/shunsuke227ono/items/e8f34c67dcffa0fa28ad https://www.javadrive.jp/start/stringbuilder/
To summarize briefly
--String is immutable and StringBuilder is mutable --String can also be described as mutable in the code (S = S + "a" etc.) --StringBuilder is more memory and time efficient for adding and inserting strings
So it seems that the use of StringBuilder is recommended, but ** I didn't see any advantages on the String side **, so that? Is it a child who doesn't need String? (Probably not).
――― 2020/02/02 postscript ――― (The title has also been changed) He pointed out in the comments and introduced ↓ good links ↓. https://qiita.com/yoshi389111/items/67354ba33f9271ef2c68
There seems to be no problem with the + operator when combining string constants or when combining with one statement. If you want to invert the string like this time, it seems better to use StringBuilder or List \ <Character >.
Added because I encountered a different problem and knowledge
ABC159 B - String Palindrome Judgment whether the character string is a palindrome (+ α). I wrote the code with the idea of whether a StringBuilder and its inverted version are the same.
Palindrome judgment code (wrong)
static boolean checkKaibun(String str){
StringBuilder t = new StringBuilder(str);
return (t.equals(t.reverse()));
}
This always returns true as far as I've tried it myself. The cause is that the StringBuilder's equals method has not been overridden.
The solution is
If you use a lot of StringBuilder comparisons in your code, it would be 1, but it seems that you also need to override the hashCode method (see below), which is annoying.
reference https://www.atmarkit.co.jp/ait/articles/0702/20/news103.html
The implementation in 2 is as follows.
Palindrome judgment code
static boolean checkKaibun(String str){
StringBuilder t = new StringBuilder(str);
return (str.equals(t.reverse().toString()));
}
Recommended Posts