java - 将随机 UUID 分配为 map 键时出现问题

标签 java collections hashmap uuid

我正在制作一个调度(调度程序?)程序。虽然我设法创建“addReport”方法,但我在显示所有报告(遍历 map )时遇到问题。我认为每次我尝试添加新元素时,它们都会被替换,因为标识符(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
}

最佳答案

您仅在构造函数中生成一次 UUID 并在 addReport 中重用它,最终,map 将仅保留同一键的最后一个条目,因此生成一个新的ID 使用

void addReport(String message, ReportType type) {
        reportMap.put(UUID.randomUUID().toString(), new Report(type, message, LocalTime.now()));
    }

关于java - 将随机 UUID 分配为 map 键时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59846115/

相关文章:

java - 线程无参构造函数有什么用?

java - 如何在鼠标位置添加面板?

java - 将字符串文本提取到另一个字符串中

java - 如何使对象集合不区分大小写?

Java:找不到符号

java - Android Activity - 最后一节课与否?

java - 从集合中删除元素

java - 需要解释 Java 中的自然顺序

c - 循环中守卫的数组索引?它实际上检查什么?

java如何组合两个hashmap而不重复条目