Jofbr
Jofbr

Reputation: 473

Java lookup enum from enum

I have two enums in two different classes (shown below):

enum State {
 NOCAR, SOLD, TO_BUY, TOYOTA, HONDA, NISSAN, BMW, MERCEDES, NO_MONEY
}

enum Car {
 TOYOTA, HONDA, NISSAN, BMW, MERCEDES
}

as you can see that the State enum contains all the possiblities of the Car enum.

So I want to do something like this:

public void sayHello(Car brand) {
  State s = ... // how to convert the brand parameter into the corresponding State enum?
  ...
  ...
}

So I want to be able to convert a given Car enum into a State enum in minimal code that is easy to understand. I know I can use a switch but that is a lot of code wastage. So please help me here.

Upvotes: 1

Views: 74

Answers (2)

GhostCat
GhostCat

Reputation: 140633

You can give the State enum a private field of type Car. Next, you add a private constructor that takes a Car object, and stores that in said field. Then you can declare your State constants like

SOLD(null), BMW(Car.BMW),...

But: conceptually, this doesn't make sense. A Car is a Car, and maybe a transaction has two properties state and car (when the state is SOLD), but the state should not reflect a car type. Meaning: whatever you do to get a Car enum from a State instance, your real problem is your design. You are duplicating things by having the "same" constants in two places already.

Your question asks how to best deal with a symptom of bad design, and the real answer is: you don't. You fix the design instead of duct taping the implementation.

Upvotes: 4

ernest_k
ernest_k

Reputation: 45339

Having a Car value, you can just use a name-based lookup:

public void sayHello(Car brand) {
  State s = State.valueOf(brand.name());
  ...
}

As long as all Car value names are in the State enum, this should always work.

Upvotes: 3

Related Questions