This is in Java – the thread “main” Java Exception in lang.stackoverflowerror
•
Java
Why do I receive a stackoverflow error?
My class –
public class Tester { int id; Tester(int id){ this.id = id; } public String toString(){ String rep = "Hex: " + this + ",Id: " + this.id; return rep; } }
Main methods –
class Driver{ public static void main(String [] args){ Tester t = new Tester(123); System.out.println(t); } }
Error –
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 !!!
Solution
You wrote:
String rep = "Hex: " + this + ",Id: " + this.id;
Simply writing in Java means that you call this indirectly toString().
I believe you are trying to override the toString () method of object, and in your toString () version, you want to print the passed ID and the hash code of the object
So replace the output
String rep = "Hex: " + this + ",Id: " + this.id;
with
String rep = "Hex: "+ this.getClass().getName().hashCode() +",Id: " + id;
You will get the output:
Hex: 1800024669,Id: 123
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码