I want to define an enumeration type with two constants whose "value" is the same. I call these two constants duplicates. Consider the following example: I want to define a list of browser types, and I want to have the literal "IE" and "InternetExplorer", as shown below:
enum Browser { CHROME("chrome"), FIREFOX("firefox"), IE("ie"), INTERNETEXPLORER("ie"); String type; Browser(String type) { this.type = type; } }
However, the following code will not be executed,
Browser a = Browser.IE; Browser b = Browser.INTERNETEXPLORER; Assert.assertTrue(a==b);
The only workaround I can come up with is to add a value() method of type Browser that returns the internal value of the browser instance. And the equality verification code will be
Assert.assertTrue(a.value()==b.value())
It is unpleasant. So does anyone have a better idea?
Why Java does not allow to redefine methods like equals() class Enum<T> ?
EDIT
Ok, thanks for the answers and comments. I agree that my original thought was directed against the purpose of the listing. I think the following changes may satisfy my need.
public enum Browser { CHROME, FIREFOX, IE; public static Browser valueOfType(String type) { if (b == null) { throw new IllegalArgumentException("No browser of type " + type); switch (type.toLowerCase()) { case "chrome": return Browser.CHROME; case "firefox": return Browser.FIREFOX; case "ie": case "internetexplorer": case "msie": return Browser.IE; default: throw new IllegalArgumentException("No browser of type " + type); } } }
Ming xue
source share