gpt4 book ai didi

读取对象时Java堆栈溢出

转载 作者:行者123 更新时间:2023-12-01 04:40:33 25 4
gpt4 key购买 nike

我正在尝试将一个对象加载到 Java 中,该对象是我从自己编写的程序中保存的。

加载时,Java 抛出堆栈溢出错误。

我加载的对象内部有大约 1000 个条目对象 ArrayList,导出时总共约为 128 Kb。

我知道当我进行太多递归调用时会发生堆栈溢出,但我不明白加载一个对象数组列表如何会导致这种情况发生?

我是一名自学成才的程序员,因此任何可以帮助我更好地理解问题的见解都将不胜感激。

这是我尝试加载的类的代码(Memboric)

    public class Memboric implements Serializable{

/**
*
* The Memboric Core stores the various databases the AI needs to function.
*
* @author Brayden McKinney
* @date 5/14/2013
*/

private static final long serialVersionUID = 4477889114653605232L;

ArrayList<String> knownWords = new ArrayList<String>();
HashMap<String, Word> thesaurus = new HashMap<String, Word>();
ArrayList<ConversationLog> conversations = new ArrayList<ConversationLog>();

File location = null;

public static Memboric load(File location){
Memboric memboric;

try{
FileInputStream file = new FileInputStream(location);
ObjectInputStream oo = new ObjectInputStream(file);
memboric = (Memboric) oo.readObject();
oo.close();
System.out.println("Memboric Core loaded and mounted successfully.");
return memboric;
}catch(FileNotFoundException fn){
System.err.println("Failed to load Memboric Core.");
}catch(InvalidClassException ic){
System.err.println("Memboric Core is incompatible.");
}catch(Exception e){
e.printStackTrace();
}

System.err.println("Creating new Memboric Core.");
return new Memboric();
}

public boolean save(File location){
this.location = location;

try{
FileOutputStream file = new FileOutputStream(location);
ObjectOutputStream oo = new ObjectOutputStream(file);
oo.writeObject(this);
oo.close();
System.out.println("Memboric Core saved successfully.");
return true;
}catch(FileNotFoundException ex){
try{
if (location.createNewFile()) save(location);
}catch(IOException exx){
exx.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}

return false;
}

它包含的姐妹类(Word):

    public class Word implements Serializable{

private static final long serialVersionUID = 790247641945230263L;

private String word;

ArrayList<String> definitions = new ArrayList<String>();
ArrayList<Word> synonyms = new ArrayList<Word>();
ArrayList<String> tags = new ArrayList<String>();
HashSet<String> links = new HashSet<String>();
}

错误本身可以在这里看到(它相当大): http://pastebin.com/46bFZYVp

此外,上面的代码被删减以节省空间(我删除了不相关的部分),但完整的类可以在这里看到:

http://pastebin.com/tptmZ2LC http://pastebin.com/3ickseFL

最佳答案

移动synonyms 外部 Word并在 Memboric 或其他一些类中跟踪它:

class Memboric {

private Map<String, Word> dictionary;
private Map<Word, Set<Word>> thesaurus;

}

基本上,从设计的角度来看,一个单词可以知道它自己的属性,但不应该知道它与其他单词的关系;每个单词都是独立的。一些更高级别的对象可以知道单词之间的关系。这可以防止对象引用之间的循环。

编辑:以上工作假设 Word 实现 hashCode()equals()正确;如果没有或者太麻烦的话就用Map<String, Set<String>>用于同义词库。

关于读取对象时Java堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16644393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com