• Post Reply Bookmark Topic Watch Topic
  • New Topic

Enums  RSS feed

 
leroy tsruya
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All!

I have some enums in my code:



I want to be able to retrieve the enum, JUN for example, by it's ordinal, 5.
So, i created a static method, inside Month:



now, I also want to make the same method in Days.
Is there a way to make a capsulate class so I won't have to code the same method in all my enums?
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Months.values() returns an array. You can use the ordinal as the index into the array to get your enum. So you don't have to loop to find it. Of course, you'll have to make sure your ordinal is correct - check to make sure the ordinal you have is within the bounds of the array or you'll get an exception. Does this satisfy your query or do you need more information?
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm sorry but Enums implicitly extend java.lang.Enum and because of that it can't extends anything else.

You could also code it like this:


And you could create a util function ala:

But I find that last one ugly because it uses reflection.
 
leroy tsruya
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wow Wouter Oet, that is exactly what I was looking for! Thanks
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!