Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
5 views
in Java by (10.2k points)

Here's my problem - I'm looking for (if it even exists) the enum equivalent of ArrayList.contains();.

Here's a sample of my code problem:

enum choices {a1, a2, b1, b2};

if(choices.???(a1)}{

//do this

Now, I realize that an ArrayList of Strings would be the better route here but I have to run my enum contents through a switch/case elsewhere. Hence my problem.

Assuming something like this doesn't exist, how could I go about doing it?

2 Answers

0 votes
by (46k points)

This should do it:

public static boolean contains(String test) {

    for (Choice c : Choice.values()) {

        if (c.name().equals(test)) {

            return true;

        }

    }

    return false;

}

This way means you do not have to worry about adding additional enum values later, they are all checked.

 If the enum is very large you could stick the values in a HashSet:

public static HashSet<String> getEnums() {

  HashSet<String> values = new HashSet<String>();

  for (Choice c : Choice.values()) {

      values.add(c.name());

  }

  return values;

}

Then you can just do: values.contains("your string") which returns true or false.

0 votes
by (1.8k points)
edited by

To verify if an enum contains a given string in java we can use a static method that will iterate through the values and compares them to the string.

For instance, let's take an enum color:

public enum Color { RED, GREEN, BLUE;
public static boolean contains(String test)
{
for (Color color : Color.values()) {
if (color.name().equalsIgnoreCase(test))
{
return true;
}
}
return false;
}
}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer
0 votes
1 answer
asked Nov 24, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...