有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何向重复的枚举类型添加多个值

我在大学里有两个enum班。java和学生。爪哇

下面是这两个类的代码片段

public enum College {

   ID("Id of College"), NAME("Name of College"), ADDRESS("Address of College");

   private final String description;

   private College(String details) {
       this.description = description;
   }

}

public enum Student {
    ROLL(College.ID, "Roll No of Student"), CLASS(College.NAME, "Class of Student"),
    PLACE(College.ADDRESS, "Place of Student"), STUDENTID(setMap());

    private final String description;
    private final College college;
    private Map<college, String> attributes;

    private Student(College college, String details) {
        this.college = college;
        this.details = details;
    }
    private Student(Map<college, String> attributes) {
        this.attributes = attributes;
        for(college key: attributes.keySet()) {
            this.college=key;
            this.description=attributes.get(key);
        }
        
    }
    
    private Map<college, String> setMap() {
        Map<college, String> map = new HashMap<college, String>();
        map.put(College.ID ,"ID of college");
        map.put(College.NAME,"Name of Student"); 
        map.put(College.ADDRESS,"Address of the College"); 
        return map;
    }
}

我的问题是,我无法在要标记多个学院枚举的学生类中添加STUDENTID枚举。 例如:

STUDENTID((College.ID ,"ID of college"),(College.NAME,"Name of Student"),(College.ADDRESS,"Address of the College"));

这只是一个示例,但我想将多个学院类枚举标记为学生类。有办法吗?请帮帮我


共 (1) 个答案

  1. # 1 楼答案

    正如@Sweeper所建议的,您需要一个合适的构造函数,请尝试下面的方法

    public enum College {
    
       ID("Id of College"), NAME("Name of College"), ADDRESS("Address of College");
    
       private final String details;
    
       College(String details) {
           this.details = details;
       }
    
    }
    
    public enum Student {
        ROLL(College.ID, "Roll No of Student"), CLASS(College.NAME, "Class of Student"),
        PLACE(College.ADDRESS, "Place of Student");
    
        private final String details;
        private College college
    
        Student(College college, String details) {
            this.college = college;
            this.details = details;
        }
    }