Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java enum doesnt store new data

I have created a small class that I use in order to contact our internal APIs.
instead of creating new connections and passing parameters, I have this class that does all the work.
The Enum is something like this

public enum EnumTypes {
    UpdateA("update",PostGetEnum.Post),
    UpdateB("update2",PostGetEnum.Post);
    private Map<String, String> values=new HashMap<String, String>();
 ....
    public void addValues(String name,String value) {
         values.put(name, value);
     }
    public Map<String, String> getValues() {
       return values;
    }
}

So i am creating an object like this

EnumTypes test = EnumTypes.UpdateA;
        test.addValues("id", "1");

It is working just fine, except something that I just noticed. When I create a second Object like so

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EnumTypes test2 = EnumTypes.UpdateA;
        test2.addValues("id", "2");

they both have the same id.

System.out.println(test.getValues());
System.out.println(test2.getValues());

2
2

Is there something that i am doing wrong?

Edit
Ok, so today I learned that Enums are Static… who knew?! (obviously I didn’t)
Thanks

>Solution :

Enum instances are static so there can only be one instance which is created at class-loading time, maybe an Enum is not what you want here.

Think of using enum the same way you would use a final static field

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading