I’m writing real-time game in Android and I’d like to do not allocate any object in main loop. The problem is String value for score.
I have class, that implements CharSequence and uses StringBuilder:
public class MyString implements CharSequence {
protected String prefix;
protected StringBuilder stringBuilder;
public MyString(String prefix) {
this.prefix = prefix;
stringBuilder = new StringBuilder(prefix);
}
public void setValue(int value) {
removeValue();
stringBuilder.append(value);
}
public void setValue(float value) {
removeValue();
stringBuilder.append(value);
}
private void removeValue() {
if (prefix == null) {
stringBuilder.setLength(0);
} else {
stringBuilder.setLength(prefix.length());
}
}
@Override
public char charAt(int index) {
return stringBuilder.charAt(index);
}
@Override
public int length() {
return stringBuilder.length();
}
@Override
public CharSequence subSequence(int start, int end) {
return null; // not necessary
}
}
The usage of this class is:
Paint paint = new Paint();
MyString myString = new MyString("Your score: ");
// Main loop
while(true) {
myString.setValue(Game.score);
canvas.drawText(myString, 0, myString.length(), 0, 0, paint);
}
The problem is, that StringBuilder.append(int) creates String object (by String.valueOf(int)) every iteration.
What is your way to solve a problem like this?
My next thought was to convert int and float to array of chars and the setValue() methods would add this array into StringBuilder. The array would be stored in MyString class and it would be created only once and then would be reused. But I can’t find way, how to convert float correctly into array of chars. The int is not problem.
Thank you for your help!
Here is some C# code that I wrote for exactly this purpose. It should be pretty simple to convert this to Java. The
minDigitsparameter causes zero-padding on the left — You can skip that if you like.