• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Enums

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
wow Wouter Oet, that is exactly what I was looking for! Thanks
 
reply
    Bookmark Topic Watch Topic
  • New Topic