Home > database >  Why the following code use String and StringBuffer in the same line?
Why the following code use String and StringBuffer in the same line?

Time:02-12

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?

CodePudding user response:

String has a constructor which takes an array of chars, hence why they create a new String first.

Then to reverse the String, they create a StringBuffer to use a built in reverse function in order to not implement their own. StringBuffer's constructor takes a String, hence why a String is made first and then a StringBuffer

CodePudding user response:

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()
);

Rewritten

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));
}

Output wise

For example:

  • alphabet gets added as alphabet8tebahpla (for coincidence ch is a non-zero integer).
  • an gets added as anna (given that ch == 0)
  • Related