我正在尝试将一个对象加载到Java中,这是我从我创建的程序中保存的。
加载时,Java引发了堆栈溢出错误。
我正在加载的对象里面有大约一千个条目对象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
此外,上面的代码被减少以节省空间(我删除了不相关的部分),但完整的类可以在这里看到:
答案 0 :(得分:0)
将synonyms
移到 Word
之外,并在Memboric或其他类中跟踪它:
class Memboric {
private Map<String, Word> dictionary;
private Map<Word, Set<Word>> thesaurus;
}
基本上,从设计的角度来看,Word可以知道它自己的属性,但不应该知道它与其他词的关系;每个单词都是独立的。一些更高级别的对象可以知道单词之间的关系。这可以防止对象引用之间的循环。
修改:上述工作假设Word正确实现了hashCode()
和equals()
;如果没有,或者它太麻烦,那么请使用Map<String, Set<String>>
作为同义词库。