StackOverflowError
原因 : 函數調用棧太深了,注意代碼中是否有了循環調用方法而無法退出的情況
原理
StackOverflowError 是一個java中常出現的錯誤:在jvm運行時的數據區域中有一個java虛擬機棧,當執行java方法時會進行壓棧彈棧的操作。在棧中會保存局部變量,操作數棧,方法出口等等。jvm規定了棧的最大深度,當執行時棧的深度大于了規定的深度,就會拋出StackOverflowError錯誤。
典型的例子:
1
2
3
4
5
6
7
8
9
10
|
public class StackOverFlowDemo { public static void Foo(){ Foo(); } public static void main(String[] args) { Foo(); } } |
今天我遇見了另外一種情況:當兩個對象相互引用,在調用toString方法時會產生這個異常,因為它們會循環調用toString方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
//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()); } } |
出現的錯誤:
toString()
說到toString()方法,在打印一個對象時,會先調用這個對象的toString()方法,例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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.
到此這篇關于Java StackOverflowError詳解的文章就介紹到這了,更多相關Java StackOverflowError內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/gentlezuo/article/details/90580116