I'm struggling with a java HashMap
. I want to return translationList
as an array with strings. Example: word : "translated word"
.
Main
class:
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
class:
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 returns:
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)
Thanks for help :)
Your translationList
method is calling itself, leading to infinite recursive calls and StackOverflowError
.
You probably intended to write something like:
public List<String> translationList(){
List<String> list = new ArrayList<>();
for ( String key : dictionary.keySet() ) {
list.add(key+" = "+dictionary.get(key));
}
return list;
}
or
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;
}
You have to first create an ArrayList
and then add String
s to it. Besides that, the if (translationList().size()<dictionary.size())
condition is pointless, even without the recursive call.
You're having a recursive call with return translationList();
. This is probably accidental. Your code was probably intended to look something like:
public ArrayList<String> translationList(){
List<String> translationList = new ArrayList<>();
for ( String key : dictionary.keySet() ) {
if(translationList().size()<dictionary.size()){
translationList.add(key+" = "+dictionary.get(key));
}
}
return translationList();
}
But an even simpler implementation can avoid extra lookups:
public List<String> translationList(){
return dictionary.entrySet()
.stream()
.map(entry -> entry.getKey() + " = " + entry.getValue())
.collect(Collectors.toList());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.