Skip to content
Advertisement

Tag: enums

Why would an Enum implement an Interface?

I just found out that Java allows enums to implement an interface. What would be a good use case for that? Answer Enums don’t just have to represent passive sets (e.g. colours). They can represent more complex objects with functionality, and so you’re then likely to want to add further functionality to these – e.g. you may have interfaces such

Pick a random value from an enum?

If I have an enum like this: What is the best way to pick one randomly? It doesn’t need to be production quality bulletproof, but a fairly even distribution would be nice. I could do something like this But is there a better way? I feel like this is something that’s been solved before. Answer The only thing I would

A for-loop to iterate over an enum in Java

I have an enum in Java for the cardinal and intermediate directions: How can I write a for loop that iterates through each of these enum values? Answer .values() You can call the values() method on your enum. This values() method is implicitly declared by the compiler. So it is not listed on Enum doc.

Convert from enum ordinal to enum type

I’ve the enum type ReportTypeEnum that get passed between methods in all my classes but I then need to pass this on the URL so I use the ordinal method to get the int value. After I get it in my other JSP page, I need to convert it to back to an ReportTypeEnum so that I can continue passing

Ways to save enums in database

What is the best way to save enums into a database? I know Java provides name() and valueOf() methods to convert enum values into a String and back. But are there any other (flexible) options to store these values? Is there a smart way to make enums into unique numbers (ordinal() is not safe to use)? Update Thanks for all

Advertisement