JAVA中StackOverflowError錯誤的解決
根據(jù)名字的意思可以大致知道它是跟函數(shù)棧有關的錯誤,就是函數(shù)棧調用太深了,可能是代碼中有了循環(huán)調用方法而無法退出的情況。而像while這樣的死循環(huán),不會報錯,程序會一直執(zhí)行下去,占用內存。
原理StackOverflowError 是一個java中常出現(xiàn)的錯誤:在jvm運行時的數(shù)據(jù)區(qū)域中有一個java虛擬機棧,當執(zhí)行java方法時會進行壓棧彈棧的操作。在棧中會保存局部變量,操作數(shù)棧,方法出口等等。jvm規(guī)定了棧的最大深度,當執(zhí)行時棧的深度大于了規(guī)定的深度,就會拋出StackOverflowError錯誤。
所以當你在一個函數(shù)再調用此函數(shù)時,而忘記設置出口就會出現(xiàn)這個錯誤。
今天我遇到的問題就是我想覆寫hash函數(shù),想要在此函數(shù)調用的結果是原來的hash函數(shù)調用的結果再隨便加一個字符串,結果就忽視了函數(shù)會一直調用下去,相當于沒有設置遞歸函數(shù)的出口,所以導致了StackOverflowError錯誤。
這是當時我的代碼
發(fā)生的錯誤
當我把函數(shù)名字改一改就能正常運行。還有原來的一些設置圖書和學生類時,這兩個類中都覆寫了toString方法,這兩個類也可以互相調用,當最后調用tostring時也會發(fā)生錯誤。
下面是我在網(wǎng)上找的一段代碼
//book和student相互循環(huán)引用public class StackOverFlowDemo { static class Student{String name;Book book; public Student(String name) { this.name = name;}//循環(huán)調用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()); } }
發(fā)生了如下錯誤
到此這篇關于JAVA中StackOverflowError錯誤的解決的文章就介紹到這了,更多相關JAVA StackOverflowError錯誤內容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
