5 Replies Latest reply: Aug 22, 2007 6:10 AM by 807600 RSS

    check element in enum

    807600
      How to check that certain element belongs to certain enum?
      public enum names{Tom,Bob, Roy,Mike};
      public String name1 = "Kate";
        • 1. Re: check element in enum
          807600
          Might try something like this
          public enum Names {
              TOM, BOB, ROY, MIKE;
          
              public static boolean contains(String name) {
                  try {
                      valueOf(name.toUpperCase());
                      return true;
                  } catch (IllegalArgumentException e) {
                      return false;
                  }
              }
          }
          Note that I've changed the case of the names you used to follow convention.

          Message was edited by:
          dwg
          • 2. Re: check element in enum
            807600
            I don't have control on enum. It's not mine.
            • 3. Re: check element in enum
              807600
              Doesn't change anything. You can still use the solution, just place the contains method somewhere else.
              Note you'll need to add names. in front of valueOf.

              And might I add that the enum you've been given breaks a bunch of the Java naming conventions.

              Message was edited by:
              dwg
              • 4. Re: check element in enum
                807600
                How to check that certain element belongs to certain
                enum?
                public enum names{Tom,Bob, Roy,Mike};
                public String name1 = "Kate";
                boolean kateExists = ( names.valueOf("Kate") != null);
                You should be able to adjust that to suit your needs. By the way, class names should begin with an Uppercase letter

                edit: doesn't work, ignore. Forgot it throws an IllegalArgumentException, as per the previous snippet

                Message was edited by:
                georgemc
                • 5. Re: check element in enum
                  Puce
                  I don't have control on enum. It's not mine.
                  Then place this method in another class and change:
                  valueOf(name.toUpperCase());
                  
                  with
                  
                  Names.valueOf(name.toUpperCase());
                  Edit: I'm too slow... ;)