Reputation: 45921
I'm developing an Android application:
I have this Enum
:
public enum Gender
{
male (0, MyApplication.getAppContext().getString(R.string.male)),
female (1, MyApplication.getAppContext().getString(R.string.female));
private final int gender;
private final String description;
Gender(int aGender, String aDescription)
{
gender = aGender;
description = aDescription;
}
public int getValue() { return gender; }
@Override
public String toString() { return description; }
/**
* Returns all values in this Enum sorted alphabetically by
* description.
* @return All values sorted.
*/
public static Gender[] getSortedVaules()
{
Gender[] sorted = values();
Arrays.sort(sorted, EnumByNameComparator.INSTANCE);
return sorted;
}
}
Imagine I have int gender = 1
. In this case, 1 is the value for Gender.female
.
I want to use gender
variable to get the index of Gender.female
enum in the array
returned by Gender.getSortedValues()
.
I think I have to use gender
variable to get an its Gender representation, in other words, to get an enum variable with Gender.female
as value. And then, use that enum variable to search on Gender.getSortedValues()
. But I don't know how to get an enum using its value.
How can I do that?
Upvotes: 0
Views: 322
Reputation: 121720
If you have an integer which is the gender
member of this enum, you should add a static method to your enum:
public static Gender getByInt(final int i)
{
for (final Gender g: values())
if (g.gender == i)
return g;
return null; // not found
}
You'll then call Gender.getByInt(...);
.
But Enum
also has .valueOf()
: Enum.valueOf(Gender.class, "male")
or Gender.valueOf("male")
for instance; beware that it throws an IllegalArgumentException
if there is no such value.
Also read about .ordinal()
. Javadoc for Enum
.
final note: naming your int gender
is confusing.
Upvotes: 3
Reputation: 22070
Remove the member field gender. You introduce a potentially non unique field in an already perfect ordinal type, which can lead to programming bugs later on.
Then just rely on the ordinal() method, when you have to serialize the enum somewhere. Use a loop and identity comparison for the lookup (as suggested by fge).
For the sorted values, use an immutable static list (or other indexed collection) instead of an array, because then you can use list.indexOf(myEnum) easily and have to sort only once.
Upvotes: 0