set.add(new String(s) + (ch == 0 ? "" : ch) + new StringBuffer(new String(s)).reverse());
I encountered this code from written by someone. It is java code. s is a char[]. set is a String set. So why does he use String and then StringBuffer?
set.add(new String(s) + (ch == 0 ? "" : ch) + new StringBuffer(new String(s)).reverse());
I encountered this code from written by someone. It is java code. s is a char[]. set is a String set. So why does he use String and then StringBuffer?
On
Let's split the 3 parts on 3 lines to compare:
set.add(
new String(s)
+ (ch == 0 ? "" : ch)
+ new StringBuffer(new String(s)).reverse()
);
It is equivalent with
String trimZero = ch == 0 ? "" : String.valueOf(ch);
set.add(String.valueOf(s) + trimZero + StringUtils.reverse(s));
Well, using Apache's StringUtils.reverse().
If s is a String it can simply added as is, for example, in an alternative way (to emphasize the different structures):
if (ch == 0) {
set.add(s + StringUtils.reverse(s));
} else {
set.add(s + String.valueOf(ch) + StringUtils.reverse(s));
}
For example:
alphabet gets added as alphabet8tebahpla (for coincidence ch is a non-zero integer).an gets added as anna (given that ch == 0)When guessing the types I would say:
ch probably is a primitive char, array of that, or CharSequeces most-likely is a String (rather than the rarely used short integer)Usually abbreviations in symbols/names are ambiguous and can be considered a code-smell.
However there seems to be a historical and accepted convention or habit, especially for temporary / looping variables like:
int iString schar chThe Java Pocket Guide, 4th Edition by Robert Liguori, Patricia Liguori, Chapter 1. Naming Conventions assorted them in a table:
Temporary variable names may be single letters such as i, j, k, m, and n for integers and c, d, and e for characters. Temporary and looping variables may be one-character names as shown in Table 1-1.
Even core Java methods have such (ambiguous) abbreviated parameter-names
Stringhas a constructor which takes an array of chars, hence why they create anew Stringfirst.Then to reverse the String, they create a
StringBufferto use a built in reverse function in order to not implement their own.StringBuffer's constructor takes a String, hence why aStringis made first and then aStringBuffer