-1

I have a simple enum that I am iterating through to check if it contains a specific value. Here is my code -

private static boolean checkCountryCode(CountryCode countryCode) {
    return Arrays.asList(CountryCodeList.values()).contains(countryCode.name());
}

This always returns false although the country code I am passing in the request is present in the list. In this case, I can't override equals since its a enum.

The countryCode in the method argument has the countryCode I am passing in the request. In my case, it is UA (Ukraine). The CountryCodeList is a list pre-populated with all the country codes in which our application runs. Some of them are on this page - http://countrycode.org/

Also, please note both CountryCode, and CountryCodeList are enums.

halfer
  • 19,824
  • 17
  • 99
  • 186
rickygrimes
  • 2,637
  • 9
  • 46
  • 69
  • Build up a static map of names to enums and check for it in there then. – Evan Knowles Mar 11 '15 at 06:24
  • 2
    I think you'll need to provide more of the surrounding code in order for people to help you. For example, we can't see the relationship between CountryCodeList and CountryCode. You could try using the debugger or printing some values in that method to see if that gives you the answer. – WW. Mar 11 '15 at 06:25
  • 2
    I don't understand. Why not just `contains(countryCode)`? What is `CountryCodeList`? – Sotirios Delimanolis Mar 11 '15 at 06:30
  • CountryCodeList has the list of all country codes. Just as the name of the class suggests. I debugged, and that's when I found this always returns false. – rickygrimes Mar 11 '15 at 06:30
  • The contains method uses the equals method don't forget about that. – Jimmy Geers Mar 11 '15 at 06:31
  • For where are you getting CountryCodeList?. I think that is the root cause of the problem. Do the types (contents of the list and the enum values) match? – TheLostMind Mar 11 '15 at 06:33
  • Can you post sample values of the list, and the countyCode.name, perhaps it's a case sensitivity issue. – owenrb Mar 11 '15 at 06:35
  • Done. Please let me know if you have any further questions. And nope, its not a case sensitivity issue. My case is similar to the issue posted here - http://stackoverflow.com/questions/20859706/java-arraylist-contain-always-return-false-although-it-contain-the-same-value. Except in my code, I can't override equals since CountryCodeList is an enum as well. – rickygrimes Mar 11 '15 at 06:41
  • 1
    Post the source code of both `CountryCodeList` and `CountryCode`. – Sotirios Delimanolis Mar 11 '15 at 06:43

1 Answers1

0

If CountryCodeList is enum, you can refactor you code to this

private static boolean checkCountryCode(CountryCode countryCode) {
   try{
      return  CountryCodeList.valueOf(countryCode.name()) != null;
   } catch (java.lang.IllegalArgumentException e) {
      return false;
   }
}
owenrb
  • 535
  • 2
  • 7