Reputation: 37
A better solution?
public String toString(byte[] array) {
if (array == null)
return "null";
StringBuilder sb = new StringBuilder(256).append('[');
for (int j = 0; j < array.length; ++j) {
sb.append(array[j]);
if (j != array.length - 1)
sb.append(", ");
}
return sb.append(']').toString();
}
A better solution? If possible a more rapid solution to perform this method
Upvotes: 1
Views: 145
Reputation: 7488
The following line:
sb.append(array[j]);
is sort of expensive, as it involves converting an int
to a character representation and at the same time keeping track of the working buffer etc.
If you can live with a result like this:
[-123, 123, 002, 000,-022, 127]
instead of
[-123, 123, 2, 0, -22, 127]
Then below method is 2 - 3 times faster on my machine:
public String toString(byte[] array) {
final char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
if (array == null) {
return "null";
}
char[] res = new char[(array.length * 5) + 1];
int abs;
int pos = 0;
res[pos++] = '[';
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
abs = - array[i];
res[pos++] = '-';
} else {
abs = array[i];
res[pos++] = ' ';
}
res[pos++] = (abs >= 100 ? '1' : '0');
int rest = (abs % 100);
res[pos++] = DIGITS[rest / 10];
res[pos++] = DIGITS[rest % 10];
res[pos++] = ',';
}
res[res.length - 1] = ']';
return new String(res);
}
Upvotes: 0
Reputation: 68715
Arrays.toString()
returns a String representation of the specified array.Maybe this should suffice:
String s1 = Arrays.toString(byte);
Upvotes: 4