add StringBuilder ; improve Object.toString

This commit is contained in:
Zack Buhman 2025-01-10 22:22:42 -06:00
parent 008690543d
commit 94556bcd97
3 changed files with 59 additions and 3 deletions

View File

@ -8,7 +8,6 @@ public class Object {
public native int hashCode();
public String toString() {
return null;
//return getClass().getName() + "@" + Integer.toString(hashCode());
return getClass().getName() + "@" + Integer.toString(hashCode());
}
}

View File

@ -0,0 +1,48 @@
package java.lang;
public class StringBuilder {
String[] strings;
int count;
public StringBuilder() {
strings = new String[0];
}
public StringBuilder(int capacity) {
strings = new String[capacity];
}
private void ensureCapacityInternal(int minimumCapacity) {
if (strings.length < minimumCapacity) {
String[] new_strings = new String[minimumCapacity + 3];
for (int i = 0; i < count; i++) {
new_strings[i] = strings[i];
}
strings = new_strings;
}
}
public StringBuilder append(String s) {
ensureCapacityInternal(count + 1);
strings[count] = s;
count += 1;
return this;
}
public String toString() {
int size = 0;
for (int i = 0; i < count; i++) {
size += strings[i].length();
}
byte[] buf = new byte[size];
int ix = 0;
for (int i = 0; i < count; i++) {
byte[] src = strings[i].getBytes();
for (int j = 0; j < src.length; j++) {
buf[ix] = src[j];
ix += 1;
}
}
return new String(buf);
}
}

View File

@ -1,8 +1,17 @@
package test;
class TestClass {
public static void main() {
static void test1() {
TestClass obj = new TestClass();
System.out.println(obj.getClass().getName());
}
static void test2() {
TestClass obj = new TestClass();
System.out.println(obj);
}
public static void main() {
test2();
}
}