Reputation: 5574
So, I recently read this post and I want to do effectively the same thing.
I didn't really care about "ugliness", etc. so I implemented one of the methods like so:
public enum Day {
Monday(1),
Tuesday(2),
Wednesday(3),
Thursday(4),
Friday(5),
Saturday(6),
Sunday(7);
public final int id;
Day(int id) {
this.id = id;
}
public static Day getByID(int id) {
Day d = null;
for (Day dTemp : Day.values())
{
if (id == dTemp)
{
d = dTemp;
break;
}
}
return d;
}
public Day getNext() {
return values()[(ordinal()+1)%values().length];
}
public Day getPrev() {
return values()[(ordinal()-1)%values().length];
}
}
But, the problem with it is in the if statement when I do:
if (id == dTemp)
It says that they are incompatible types. What should I do to fix it?
Upvotes: 1
Views: 1339
Reputation: 19027
if(id == dTemp.id)
Should work.
Alternatively try with the ordinal()
method of enum
.
public final int ordinal()Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.
Returns: the ordinal of this enumeration constant. See.
Well, I copied your code and tested accordingly.
Both
if (id == dTemp.ordinal()+1)
and
if(id == dTemp.id)
worked fine and produced as expected. The statement
System.out.println(Day.Friday.getByID(1));
produces Monday.
Upvotes: 1
Reputation: 88707
Use if ( id == dTemp.id )
. Enums are classes and enum values are objects not ints and thus can't be cast (neither explicitly nor implicitly) to an int
.
Alternatively, note that enums have an ordinal, i.e. an id of their position. In your example, Monday
would have the ordinal 0 and Sunday
would have the ordinal 6. You access the ordinal by calling the ordinal()
method.
Thus if id
is one-based you could do the following instead:
public static Day getByID(int id) {
//check id is between 1 and 7, I'll leave that for you
return Day.values()[id - 1];
}
Note that you might want to cache Day.values()
in a private static variable and access that cached array then.
Btw, where's the string you mention in your question?
Upvotes: 2