开发者

Comparing a string to a number of strings (best Data Structure)

开发者 https://www.devze.com 2023-03-31 23:25 出处:网络
I have an an array which I can get the string name from. arr[i].getName(); I want a way to compare this to a number of strings I currently have them them in an Enum as follows:

I have an an array which I can get the string name from.

arr[i].getName();

I want a way to compare this to a number of strings I currently have them them in an Enum as follows:

public enum BlockManValEnum {

    SecurityID("SecurityID"),
    BlockStatus("BlockStatus"),
    Side("Side"),
    GTBookingInst("GTBookingInst");

    private String name;

    private BlockManValEnum(String name) {
        this.name = name;
    }

    public String toString() {
        return this.name;
    }


}

I want a way to check the element in the array if it matches one of these attributes then perfor开发者_开发技巧m extra functionallity if it does not match do not worry about it. I know enum is the total wrong way to store this.

However. The only way I can think around this is to create a map with a String key which will just return a true boolean. (this seems kinda dirty)


Instead of using a Map which maps to a true Boolean, you can just use a Set, and check if your element is in it or not. [and activate the functionality if it is]


public enum BlockManValEnum {

    SecurityID("SecurityID"),
    BlockStatus("BlockStatus"),
    Side("Side"),
    GTBookingInst("GTBookingInst");

    private static Set<String> names = new HashSet<String> {{
      for(BlockManValEnum e : BlockManvalEnum.values()) {
         add(e.toString());
      }
    }};

    private static boolean contains(String name) {
      return names.contains(name);
    }

    private String name;

    private BlockManValEnum(String name) {
        this.name = name;
    }

    public String toString() {
        return this.name;
    }
}

here is how you could use this:

if (BlockManValEnum.contains(arr[i].getName())) {
  // some extra functionality...
}


You're close... a Map without values is called a Set. Use a HashSet. Set has a "boolean contains()" method which is what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消