Java HashMap遍历问题:translationList方法栈溢出报错求助
解决Java HashMap中translationList方法的StackOverflowError问题
嘿,我一眼就看出问题出在哪了——你的translationList()方法陷入了无限递归,这才导致了StackOverflowError!让我给你拆解一下原因,再帮你修复代码。
错误原因分析
看你写的translationList()方法:
public ArrayList<String> translationList(){ for ( String key : dictionary.keySet() ) { if(translationList().size()<dictionary.size()){ translationList().add(key+" = "+dictionary.get(key)); } } return translationList(); }
你在方法里反复调用translationList():判断条件里调用、添加元素时调用、最后返回时还调用。每一次调用都会重新执行整个方法,永远不会终止,直到Java的调用栈被耗尽,抛出栈溢出错误。
而且你原来的格式也不符合需求(需要word : "translated word"而不是word = translated word),这部分也得调整。
修复后的代码
我们需要在方法内部创建一个本地的ArrayList,遍历HashMap的键值对,按照要求的格式生成字符串并添加到列表中,最后返回这个列表即可。修正后的Dictionary类如下:
import java.util.ArrayList; import java.util.HashMap; public class Dictionary { private HashMap<String, String> dictionary = new HashMap<String, String>(); public Dictionary(){}; public String translate(String word){ if(dictionary.containsKey(word)){ return dictionary.get(word); } return null; } public void add(String word, String translation){ dictionary.put(word,translation); } public int amountOfWords() { return dictionary.size(); } public ArrayList<String> translationList(){ // 创建一个新的ArrayList来存储结果 ArrayList<String> resultList = new ArrayList<>(); // 遍历HashMap的键值对 for (String key : dictionary.keySet()) { // 按照要求的格式生成字符串:word : "translated word" String entry = key + " : \"" + dictionary.get(key) + "\""; resultList.add(entry); } return resultList; } }
运行验证
用你原来的Main类运行,输出结果会是:
apina : "monkey" banaani : "banana" cembalo : "harpsichord"
完全符合你想要的格式,也不会再出现栈溢出错误啦。
内容的提问来源于stack exchange,提问作者Doseq
相关产品推荐
相关产品推荐

