我在用Java HashMap
挣扎。我想将translationList
作为带有字符串的数组返回。示例:word : "translated word"
。Main
类:
public static void main(String[] args) {
Dictionary dictionary = new Dictionary();
dictionary.add("apina", "monkey");
dictionary.add("banaani", "banana");
dictionary.add("cembalo", "harpsichord");
ArrayList<String> translations = dictionary.translationList();
for(String translation: translations) {
System.out.println(translation);
}
}
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(){
for ( String key : dictionary.keySet() ) {
if(translationList().size()<dictionary.size()){
translationList().add(key+" = "+dictionary.get(key));
}
}
return translationList();
}
Java返回:
Exception in thread "main" java.lang.StackOverflowError
at java.base/java.util.HashMap$KeyIterator.<init>(HashMap.java:1515)
at java.base/java.util.HashMap$KeySet.iterator(HashMap.java:917)
at Dictionary.translationList(Dictionary.java:21)
at Dictionary.translationList(Dictionary.java:22)
感谢帮助 :)
最佳答案
您的translationList
方法正在调用自身,从而导致无限递归调用和StackOverflowError
。
您可能打算编写类似以下内容的内容:
public List<String> translationList(){
List<String> list = new ArrayList<>();
for ( String key : dictionary.keySet() ) {
list.add(key+" = "+dictionary.get(key));
}
return list;
}
要么
public List<String> translationList(){
List<String> list = new ArrayList<>();
for ( Map.Entry<String,String> entry : dictionary.entrySet() ) {
list.add(entry.getKey()+" = "+entry.getValue());
}
return list;
}
您必须先创建一个
ArrayList
,然后向其中添加String
。除此之外,即使没有递归调用,if (translationList().size()<dictionary.size())
条件也没有意义。