java中的this造成StackOverflowError

西北地的风 2009-05-08 06:53:10
如题:
public class ShiftTest {
String i = "3";

public static void main(String[] args) {

ShiftTest st = new ShiftTest();
System.out.println(st.toString());
}

/**
* StackOverflowError
*/
public String toString(){
//return this + "@" + this.hashCode();
return this + this.i;
}

}
运行结果为:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.valueOf(String.java:2615)
at java.lang.StringBuilder.append(StringBuilder.java:116)
即栈溢出错误,请问是怎么造成的? 是this会反复调用自身的构造函数吗?
...全文
117 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
西北地的风 2009-06-03
  • 打赏
  • 举报
回复
多谢楼上各位的关注哈
zhangpeixv 2009-05-08
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ZangXT 的回复:]
public String toString(){
//return this + "@" + this.hashCode();
return this + this.i;
}
这里this +这部分,会把this表示的对象转换为其字符串表示,自然要调用其toString()方法,也就是调用自身(递归)

无穷递归,导致栈溢出。
[/Quote]
子子孙孙无穷尽也
qusic 2009-05-08
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ZangXT 的回复:]
public String toString(){
//return this + "@" + this.hashCode();
return this + this.i;
}
这里this +这部分,会把this表示的对象转换为其字符串表示,自然要调用其toString()方法,也就是调用自身(递归)

无穷递归,导致栈溢出。
[/Quote]
就是这个样子滴
辛鹤 2009-05-08
  • 打赏
  • 举报
回复
ding 2楼
台城柳月 2009-05-08
  • 打赏
  • 举报
回复
public String toString(){
return this + this.i;
}

是这里,+号两边被当做String处理,
而this转为String就是调用toString方法,
这就成了死循环。
GeekZFZ 2009-05-08
  • 打赏
  • 举报
回复
看看这个就可以:

public class ShiftTest {
public String i = "3";

public static void main(String[] args) {

ShiftTest st = new ShiftTest();
System.out.println(st.toString());
}

/**
* StackOverflowError
*/
public String toString(){
//return this + "@" + this.hashCode();
return this.i ;
}

}

不知道你最后的这个是返回什么??
return this+this.i ;
ZangXT 2009-05-08
  • 打赏
  • 举报
回复
public String toString(){
//return this + "@" + this.hashCode();
return this + this.i;
}
这里this +这部分,会把this表示的对象转换为其字符串表示,自然要调用其toString()方法,也就是调用自身(递归)

无穷递归,导致栈溢出。

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧