Yvonne Wilkins wrote:I want to change some existing code that used to ask a simple comparison to now ask if something exists in the String array. (This is a totally made of situation)
As the others have said, there are
many ways to do what you want, but two spring to mind:
The first (my preference) is to make them classes, viz:
Then you can use the
instanceof operator, viz:
if (cat instanceof Siamese || cat instanceof Persian || ... ) { ...
The second is to use an
enum of Cat types, and have each Cat instance know it's own type, eg:
and then the check would be something like
if (cat.type() == Cat.Type.Siamese || cat.type() == Cat.Type.Persian || ... ) { ...
and the nice thing about enums is that you can use a
switch statement if you have a lot of them to check.
However, the whole setup has a rather "procedural feel" to it.
But whatever you do,
get away from using Strings. They make very poor substitutes for proper classes.
If you absolutely have to deal with a String array of possible types, the
enum option may be a bit easier to convert. It may also be able to handle cross-breeds more easily (see EnumSet).
However, the great advantage of the first solution is that you can use
polymorphism to implement breed-based behaviour
without the need for any 'if' statements.
Hope all the above hasn't confused you too much
.
Winston