Java StackOverflowError詳解
原因 : 函數(shù)調(diào)用棧太深了,注意代碼中是否有了循環(huán)調(diào)用方法而無法退出的情況
原理StackOverflowError 是一個java中常出現(xiàn)的錯誤:在jvm運行時的數(shù)據(jù)區(qū)域中有一個java虛擬機棧,當執(zhí)行java方法時會進行壓棧彈棧的操作。在棧中會保存局部變量,操作數(shù)棧,方法出口等等。jvm規(guī)定了棧的最大深度,當執(zhí)行時棧的深度大于了規(guī)定的深度,就會拋出StackOverflowError錯誤。
典型的例子:
public class StackOverFlowDemo { public static void Foo(){Foo(); } public static void main(String[] args) {Foo(); }}
今天我遇見了另外一種情況:當兩個對象相互引用,在調(diào)用toString方法時會產(chǎn)生這個異常,因為它們會循環(huán)調(diào)用toString方法。
//book和student相互循環(huán)引用public class StackOverFlowDemo { static class Student{String name;Book book;public Student(String name) { this.name = name;}//循環(huán)調(diào)用toString方法@Overridepublic 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;}@Overridepublic 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()); }}
出現(xiàn)的錯誤:
說到toString()方法,在打印一個對象時,會先調(diào)用這個對象的toString()方法,例如:
public class toStringDemo { static class A{@Overridepublic 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內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. Python TestSuite生成測試報告過程解析2. python讓函數(shù)不返回結果的方法3. python之cur.fetchall與cur.fetchone提取數(shù)據(jù)并統(tǒng)計處理操作4. JSP之表單提交get和post的區(qū)別詳解及實例5. python實現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例6. PHP循環(huán)與分支知識點梳理7. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題8. chat.asp聊天程序的編寫方法9. 低版本IE正常運行HTML5+CSS3網(wǎng)站的3種解決方案10. jsp實現(xiàn)登錄驗證的過濾器
