san*_*011 0 java collections uuid hashmap
我正在制作一个调度(调度员?)程序。当我设法创建“addReport”方法时,我在显示所有报告(遍历地图)时遇到了问题。我认为每次我尝试添加新元素时,它们都会被替换,因为标识符 (UUID) 是相同的。你怎么看,或者可能是不同的东西?
public class Dispatching {
private String identificator;
private Map<String, Report> reportMap;
public Dispatching() {
this.identificator = UUID.randomUUID().toString();
this.reportMap = new HashMap<>();
}
void addReport(String message, ReportType type) {
reportMap.put(identificator, new Report(type, message, LocalTime.now()));
}
void showReports() {
for (Map.Entry element : reportMap.entrySet()) {
System.out.println("uuid: " + element.getKey().toString()
+ " " + element.getValue().toString());
}
}
}
public class Report {
ReportType reportType;
String reportMessage;
LocalTime reportTime;
public Report(ReportType reportType, String reportMessage, LocalTime reportTime) {
this.reportType = reportType;
this.reportMessage = reportMessage;
this.reportTime = reportTime;
}
@Override
public String toString() {
return "Report{" +
"reportType=" + reportType +
", reportMessage='" + reportMessage + '\'' +
", reportTime=" + reportTime +
'}';
}
}
public class Main {
public static void main(String[] args) {
Dispatching dispatching = new Dispatching();
dispatching.addReport("heeeeelp",ReportType.AMBULANCE);
dispatching.addReport("poliiiice",ReportType.POLICE);
dispatching.addReport("treeee",ReportType.OTHER);
dispatching.showReports();
}
}
public enum ReportType {
AMBULANCE,
POLICE,
FIRE_BRIGADE,
ACCIDENT,
OTHER
}
Run Code Online (Sandbox Code Playgroud)
您UUID在构造函数中生成唯一一次并在内部重用它addReport,最终,map 将只保留同一键的最后一个条目,因此使用生成一个新 ID
void addReport(String message, ReportType type) {
reportMap.put(UUID.randomUUID().toString(), new Report(type, message, LocalTime.now()));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
217 次 |
| 最近记录: |