我的哈希地图包含3个参数aName
aDate
aTime
我有一个WhatsOn方法,我试图配置,如果今天实际上今天只打印今天的文本形式的键值对。 (并忽略所有其他键值对)
我想知道这是否最好通过使用日期类的迭代完成,还是可以在没有的情况下实现。我的两个课程如下:
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("Its saturday, just relax", "140418", "0900");
for (Map.Entry<Integer,Activity> entry: activities.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
System.out.println(key + " " + value);
}
}
//instance variables for WhatsOn class
private String today;
private int nextId;
private static Map<Integer, Activity> activities;
// the constructor for the WhatsOn class
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
}
public void whatsOnToday () {
// needs configured
}
}
Activity.java
public class Activity {
private String name;
private String date;
private String time;
//constructor
Activity(String name, String date, String time) {
this.name = name;
this.date = date;
this.time = time;
}
//to string method
public String toString(){
return getName() + getDate() + getTime();
}
//getters and setters
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;
}
}
答案 0 :(得分:1)
您没有利用Write_Text
的潜力。如果您将日期作为关键,那么很容易检索今天的所有活动。因此,您的HashMap
声明如下:
HashMap
为了添加活动,方法将更改为:
HashMap<String, List<Activity>> activities = new HashMap<>();
并删除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
if(activities.containsKey(aDate)){
activities.get(aDate).add(actToAdd);
} else {
ArrayList<Activity> activitiesList = new ArrayList<>();
activitiesList.add(actToAdd);
activities.put(aDate, activitiesList); //Add this instance to your Map
}
}
属性。
要检索今天nextId
的列表,只需执行Activity
。正如其他人提到的,请使用activities.get(aDate)
代替LocalDate
作为日期。