为什么我收到stackoverflow错误?
我的课 –
public class Tester { int id; Tester(int id){ this.id = id; } public String toString(){ String rep = "Hex: " + this + ",Id: " + this.id; return rep; } }
主要方法 –
class Driver{ public static void main(String [] args){ Tester t = new Tester(123); System.out.println(t); } }
错误 –
Exception in thread "main" java.lang.StackOverflowError at java.lang.String.length(Unknown Source) at java.lang.AbstractStringBuilder.append(Unknown Source) at java.lang.StringBuilder.append(Unknown Source) at java.lang.StringBuilder.<init>(Unknown Source) at com.examscam.model.Tester.toString(Tester.java:13) at java.lang.String.valueOf(Unknown Source) at java.lang.StringBuilder.append(Unknown Source) ---------REPEAT !!!
解决方法
你写了:
String rep = "Hex: " + this + ",Id: " + this.id;
在java中简单地写这意味着你间接调用this.toString().
我相信您正在尝试覆盖Object的toString()方法,并且在您的toString()版本中,您希望打印已传递的ID以及对象的哈希码.
所以要取代输出
String rep = "Hex: " + this + ",Id: " + this.id;
同
String rep = "Hex: "+ this.getClass().getName().hashCode() +",Id: " + id;
你会得到输出:
Hex: 1800024669,Id: 123