I am very new to enums and the whole principle is a bit confusing to me.
I want to have a priceObject which is constructed by a price the enumtype and the name.
As you can see with PreisObject2 I want to check the enum by the value and not by the name as in PreisObject1.
Is this somehow so possible? Or do I have to use a if-else or switch statement to do something like this?
E Armitage wrote:All enums automatically have access to a valueOf method that does this. You will just need to call Price.valueOf
That only uses the name of the Enum, so "fixed" in this example. Supplying 'f' would yield no result, hence the need for a "roll your own" valueOf.
Campbell Ritchie wrote:Can you actually write your own valueOf method for enums?
You can add one if the signature is different from the implicitly provided one. If you need it to take a String then you would have to use a different name, otherwise you get the enum already defines the method valueOf(String) implicitly error.
Kevin Olome wrote:Is this somehow so possible? Or do I have to use a if-else or switch statement to do something like this?
1. Yes, 2. No - but it takes a bit of thought.
The main question is: Why do you have a char that simply duplicates exactly what the enum already provides you - ie, identifying a "price type"?
If it's only for reading stuff in (or indeed, persisting price information) then use the name of the Price instance, rather than a character. Converting a name to and from a single character just to save space is a false economy in these days of terabyte disks and gigabyte machines.
The only reason I can think of that you might need it is that you've been given a file format that uses them; and if that's the case, then the person who designed it should be roasted slowly over an open fire.
So: my advice would be to get rid of that char altogether, and simply use Price everywhere - ie:
PreisObject p2 = new PreisObject(2, Price.fixed, "Test2");
otherwise you'll be forever converting from chars to Prices and back.
what's more "readable" to you:
if (someObject.price == 'f') ...
if (someObject.price == Price.fixed) ...
And just a minor style point: enum names are usually uppercase, so it should be:
if (someObject.price == Price.FIXED) ...
It's only a convention, but it does help to highlight the fact that it's an enum, rather than just a regular variable.