I have code I am working on, but I am having issues populating the HashMap of HashMaps. The declaration goes as thus;
HashMap<Games, HashMap<Store, Integer>> myMap = new HashMap<Games, HashMap<Store, Integer>>();
Where Game
and Store
are separate object classes, with only a class variable title.
How do I create instances of the objects in the HashMaps and also populate the two hashmaps. Because I need to tag an Integer to the game in a particular store. Whereas there are different stores and different games in each store.
Thanks in Advance
Edit
Games Class
package gameStore;
public class Games {
private String title;
public Games(String inTitle){
setTitle(inTitle);
}
private String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}
}
Stores Class
package gameStore;
public class LocalStores {
private String nameOfStore;
public LocalStores(String inNameOfStore){
setNameOfStore(inNameOfStore);
}
private void setNameOfStore(String nameOfStore){
this.nameOfStore = nameOfStore;
}
}
I would do something like this:
void addToMap(Games games, Store store, int value) {
HashMap<Store,Integer> m = myMap.get(games);
if (m == null) {
m = new HashMap<Store,Integer>();
myMap.put(games, m);
}
m.put(store, value);
}
UPDATE:
Since Games and Store are both used as keys to a HashMap, I would recommand that you add the hashCode and equals methods:
Games:
public int hashCode() {
return title.hashCode();
}
public boolean equals(Object obj) {
if (!(obj instanceof Games)) {
return false;
}
Games other = (Games)obj;
return title.equals(other.title);
}
LocalStores:
public int hashCode() {
return nameOfStore.hashCode();
}
public boolean equals(Object obj) {
if (!(obj instanceof LocalStores)) {
return false;
}
LocalStores other = (LocalStores)obj;
return nameOfStore.equals(other.nameOfStore);
}
Now, to keep it simple, let's say that each line of your input file contains three fields separated by tabs: the games' title, the store's name, and the integer value. You would read it as follows:
InputStream stream = new FileInputStream("myfile");
try {
Reader reader = new InputStreamReader(stream, "UTF-8"); // or another encoding
try {
BufferedInputStream in = new BufferedInputStream(reader);
try {
String line = in.readLine();
while (line != null) {
String[] fields = line.split("[\\t]");
if (fields.length == 3) {
addToMap(new Games(fields[0]), new LocalStores(fields[1]), Integer.parseInt(fields[2]));
}
line = in.readLine();
}
} finally {
in.close();
}
} finally {
reader.close();
}
} finally {
stream.close();
}
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.