java - Trying to add Array of Strings via Another Class using HashMap -
basically know how arraylist array i'm totally stumped.
import java.util.hashmap; import java.util.set; import java.util.iterator; import java.util.map; import java.util.collection; public class nobelprizewinners { private hashmap<string, prizewinners[]> winners; public nobelprizewinners() { winners = new hashmap<string, prizewinners[]>(); prizewinners[] name = new prizewinners[3]; name[0] = new prizewinners("hey" , "hey"); winners.put("2008", name); } } public void displayallyearsandwinners(){ set<string> years = winners.keyset(); for(string year : years){ prizewinners [] list = winners.get(year); for(prizewinners[] names : list){ system.out.println(year + " " + names); } } } this returns memory address not actual strings (the prizewinners class has 2 string parameters in constructor, 2 set methods first , last name)
i feel i'm pretty close returns "2008" 3 times memory address or null other 3 times (as haven't added other 2 arrays yet still testing see if works)
any appreciated, feel name or method need call i'm not sure on.
the first issue loop should following:
for (string year: years) { prizewinners[] list = winners.get(year); (prizewinners names: list) { system.out.println(year + " " + names); } } because retrieve list array, for-each loop returns prizewinners each iteration, not another array.
this line:
system.out.println(year + " " + names); is equivalent following:
system.out.println(year.tostring() + " " + names.tostring()); since year string, tostring() method returns value, expected.
but names array. tostring() method directly inherited object , prints memory address of names.
the cleanest way solve override tostring() in class prizewinners. lets decide string representation of class should be.
public string tostring() { return this.firstname + ", " + this.lastname; } now, when implicit tostring() called on names instance of prizewinners, you'll expected output.
Comments
Post a Comment