I am experimenting with the toString() method on a hash map that I have created for a small application. The map stores three params aName
aDate
aTime
.
However when I run my for-loop it merely prints out the hash code for the map rather than a textual representation which I need for each key value pair.
for (Integer name: activities.keySet()) {
String key =name.toString();
String value = activities.get(name).toString();
System.out.println(key + " " + value);
}
I was wondering where I am going wrong with this function. Any steering would be appreciated. My 2 classes are below.
WhatsOn.java
import java.util.*;
public class WhatsOn {
public static void main(String[] args) {
WhatsOn alexa; // create an instance of the WhatsOn class
alexa = new WhatsOn();
alexa.addActivity("wash car","010117","0900");
alexa.addActivity("go shopping","020117","1000");
alexa.addActivity("return sale items","010117","1000");
alexa.addActivity("back to work", "040117", "0900");
for (Integer name: activities.keySet()) {
String key =name.toString();
String value = activities.get(name).toString();
System.out.println(key + " " + value);
}
}
private String today;
private int nextId;
private static Map<Integer, Activity> activities;
public WhatsOn() {
activities = new HashMap<Integer, Activity>();
today = "010117";
nextId = 1;
System.out.println("if you see this, the constructor is working");
}
// This method should create an instance of Activity class and then add it to the map referenced by the current value of nextId as the key
public void addActivity (String aName, String aDate, String aTime) {
Activity actToAdd = new Activity(aName, aDate, aTime); //create a new instance of the activity called actToAdd, this is a local var that stores methods arguments
activities.put(nextId, actToAdd); //Add this instance to your Map
nextId++; //increase the nextId
}
}
Activity.java
public class Activity {
private String name;
private String date;
private String time;
Activity(String name, String date, String time) {
this.name = name;
this.date = date;
this.time = time;
}
public void setDate(String aDate) {
this.date = aDate;
}
public void setTime(String aTime) {
this.time = aTime;
}
public void setName(String aName) {
this.name = aName;
}
public String getDate() {
return this.date;
}
public String getTime() {
return this.time;
}
public String getName() {
return this.name;
}
}