Home > Enterprise >  How to convert StringBuilder[] to String[]
How to convert StringBuilder[] to String[]

Time:11-09

I have an array of StringBuilder objects as shown below.

StringBuilder[] sbCmd = new StringBuilder[5];
int cntr = 0;
sbCmd[cntr  ].append("add");
sbCmd[cntr  ].append("sub");
sbCmd[cntr  ].append("mul");
sbCmd[cntr  ].append("div");
sbCmd[cntr  ].append("mod");

Now I have a function which takes an array of Strings as input as shown below.

ConfigureMathOperation(String[] array)
{
  //Do some work
}

How can I call the same? I'm trying to avoid String[] here because it is immutable (I have some sensitive data which needs to be cleared after function call).

Do I have to call toString for each StringBuilder object stored in array? Sample code snippet would really help as I'm new to Java.

For example i want to call as below, but its not working since i'm not aware how to call for each StringBuilder object.

ConfigureMathOperation(sbCmd.toString());

CodePudding user response:

To answer the question directly, you can use streams to convert your StringBuilder[] to String[] easily enough:

String[] arr = Arrays.stream(sbCmd).map(StringBuilder::toString).toArray(String[]::new);

...but:

I'm trying to avoid String[] here because it is immutable (I have some sensitive data which needs to be cleared after function call).

You can't avoid it. If you have a library function that takes a String array, then you have to provide a String array - and that obviously requires the use of Strings.

Your only other option is to fork the library and remove the use of strings. Note that this is likely to be a time-consuming, and tedious operation however - it's not nearly as simple as just making sure no string parameters are passed in (as the library function could easily call sb.toString() and obtain a string.)

The much more pragmatic approach would be not to worry about strings being left in memory, instead running your code in a secure, isolated environment, and letting the environment do its job.

  • Related