StackOverflowError

StackOverflowError

原因 : 函数调用栈太深了,注意代码中是否有了循环调用方法而无法退出的情况

原理

StackOverflowError 是一个java中常出现的错误:在jvm运行时的数据区域中有一个java虚拟机栈,当执行java方法时会进行压栈弹栈的操作。在栈中会保存局部变量,操作数栈,方法出口等等。jvm规定了栈的最大深度,当执行时栈的深度大于了规定的深度,就会抛出StackOverflowError错误。

典型的例子:


public class StackOverFlowDemo {

    public static void Foo(){
        Foo();
    }

    public static void main(String[] args) {
        Foo();
    }
}

今天我遇见了另外一种情况:当两个对象相互引用,在调用toString方法时会产生这个异常,因为它们会循环调用toString方法。

//book和student相互循环引用
public class StackOverFlowDemo {

    static class Student{
        String name;
        Book book;

        public Student(String name) {
            this.name = name;
        }
        //循环调用toString方法
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", book=" + book +
                    '}';
        }
    }

    static class Book {
        String isbn;
        Student student;

        public Book(String isbn, Student student) {
            this.isbn = isbn;
            this.student = student;
        }

        @Override
        public String toString() {
            return "Book{" +
                    "isbn='" + isbn + '\'' +
                    ", student=" + student +
                    '}';
        }
    }

    public static void main(String[] args) {
        Student student=new Student("zhang3");
        Book book=new Book("1111",student);
        student.book=book;
        System.out.println(book.toString());
    }

}

出现的错误:
stackoverflow

toString()

说到toString()方法,在打印一个对象时,会先调用这个对象的toString()方法,例如:

public class toStringDemo {

    static class A{
        @Override
        public String toString() {
            System.out.print("I ");
            return "";
        }
    }

    public static void main(String[] args) {
        A a=new A();
        System.out.println("love you."+a);
    }
}

会输出:

I love you.

原文章地址: https://gentlezuo.github.io/2019/04/21/java-StackOverflowError/

  • 20
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值