将特定字符串映射到常量整数?

发布于 2024-10-01 02:21:42 字数 497 浏览 5 评论 0原文

给定一组特定的字符串,将它们映射到相应的整数组的最佳方法是什么?假设我有一个类,其中有一些内部使用的整数常量,但需要获取传入的外部字符串并确定它们映射到的正确对应的整数常量。

这是一个简化的示例:

public class Example {
    public static final int ITEM_APPLE = 0;
    public static final int ITEM_BANANA = 1;
    public static final int ITEM_GRAPE = 3;

    public void incomingData(String value) {
        // Possible values would be "apple", "banana", and "grape" in this case.
    }
}

从该值转换为其相应的整数常量的最合适方法是什么?哈希映射?或者有什么方法可以在静态成员中定义这些映射吗?另一个想法?

Given a specific set of strings, what's the best way to map them to a corresponding set of integers? Say I have a class with a few integer constants that I use internally, but need to take incoming external strings and determine the correct corresponding integer constant they map to.

Here's a simplified example:

public class Example {
    public static final int ITEM_APPLE = 0;
    public static final int ITEM_BANANA = 1;
    public static final int ITEM_GRAPE = 3;

    public void incomingData(String value) {
        // Possible values would be "apple", "banana", and "grape" in this case.
    }
}

What would the most appropriate approach be to go from that value to its corresponding integer constant? A HashMap? Or is ther any way to define these mappings in a static member? Another idea?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

北方的巷 2024-10-08 02:21:42

我会使用 HashMap,因为它最接近您想要实现的目标,因此是一个可维护的解决方案。您可以定义静态 HashMap:

Class Example {
    public static final int ITEM_APPLE = 0;
    public static final int ITEM_BANANA = 1;
    public static final int ITEM_GRAPE = 3;

    private static final Map<String, Integer> fruitCodes = new HashMap<String, Integer>();

    static {
        fruitCodes.put("apple", ITEM_APPLE);
        fruitCodes.put("banana", ITEM_BANANA);
        // ...
    }


    public void incomingData(String value) {
        // Possible values would be "apple", "banana", and "grape" in this case.
        Integer code = fruitCodes(value);

        if (null == code) {
            throw new IllegalArgumentException("Forbidden fruit: " + value);
        }
    }
}

I would use a HashMap as that is closest to what you want to achieve, and therefore a maintainable solution. You can define a static HashMap:

Class Example {
    public static final int ITEM_APPLE = 0;
    public static final int ITEM_BANANA = 1;
    public static final int ITEM_GRAPE = 3;

    private static final Map<String, Integer> fruitCodes = new HashMap<String, Integer>();

    static {
        fruitCodes.put("apple", ITEM_APPLE);
        fruitCodes.put("banana", ITEM_BANANA);
        // ...
    }


    public void incomingData(String value) {
        // Possible values would be "apple", "banana", and "grape" in this case.
        Integer code = fruitCodes(value);

        if (null == code) {
            throw new IllegalArgumentException("Forbidden fruit: " + value);
        }
    }
}
看海 2024-10-08 02:21:42

是的,使用枚举。您可以为每个枚举分配一个整数值,或者仅使用 ordinal()

public enum ExampleEnum {
    ITEM_APPLE(0), ITEM_BANANA(1), ITEM_GRAPE(3);

    private final int intValue;

    private ExampleEnum (int intValue) {
      this.intValue = intValue;
    }

    public int intValue() {
      return intValue;
    }
}

然后使用 ExampleEnum.valueOf("ITEM_APPLE").intValue() 将 String 解析为 int

如果 int 值是连续的并且从零开始,您可以完全删除 intValue 字段:

public enum ExampleEnum {
    ITEM_APPLE, ITEM_BANANA, ITEM_GRAPE;
}

只需使用 ExampleEnum.valueOf("ITEM_APPLE").ordinal()

Yes, use an enum. You can assign each enum an integer value, or just use ordinal()

public enum ExampleEnum {
    ITEM_APPLE(0), ITEM_BANANA(1), ITEM_GRAPE(3);

    private final int intValue;

    private ExampleEnum (int intValue) {
      this.intValue = intValue;
    }

    public int intValue() {
      return intValue;
    }
}

then use e.g. ExampleEnum.valueOf("ITEM_APPLE").intValue() to resolve String to int.

If the int values are sequential and zero-based, you can get rid of the intValue field altogether:

public enum ExampleEnum {
    ITEM_APPLE, ITEM_BANANA, ITEM_GRAPE;
}

and just use ExampleEnum.valueOf("ITEM_APPLE").ordinal()

没有心的人 2024-10-08 02:21:42

你“可以”使用反射,例如:

Example.class.getField("ITEM_" + input.toUpperCase()).getInt(null);

但是,你应该考虑使用枚举,或者如果没有太多可能性,只需使用一组 else if 语句...

you 'could' use reflection eg:

Example.class.getField("ITEM_" + input.toUpperCase()).getInt(null);

however, you should consider using Enums or if there aren't too many possibilities just use a set of else if statements...

ゞ记忆︶ㄣ 2024-10-08 02:21:42

我还建议使用 Enum 方法,尽管 ExampleEnum.valueOf("ITEM_APPLE").ordinal() 必须进行字符串比较才能得到答案,而 HashMap 会给你带来 O(1) 的复杂度。

可能是一个危险的想法,但只是为了好玩(这个怎么样):

class Example {
    public static final int ITEM_APPLE = "apple".hashCode();
    public static final int ITEM_BANANA = "banana".hashCode();
    public static final int ITEM_GRAPE = "grape".hashCode();

    public int incomingData(String value) {
        return value.hashCode();
    }

    public static void main(String[] args) {
        Example x = new Example();
        if (ITEM_APPLE == x.incomingData("apple"))
            System.out.println("ITEM_APPLE");
    }
    }
}

您只需确保字符串值的哈希码不会冲突;-)

I also suggest an Enum method, although ExampleEnum.valueOf("ITEM_APPLE").ordinal() will have to do string comparisons to get to the answer while a HashMap will give you an O(1) complexity.

Probably a dangerous idea but just for fun (how about this):

class Example {
    public static final int ITEM_APPLE = "apple".hashCode();
    public static final int ITEM_BANANA = "banana".hashCode();
    public static final int ITEM_GRAPE = "grape".hashCode();

    public int incomingData(String value) {
        return value.hashCode();
    }

    public static void main(String[] args) {
        Example x = new Example();
        if (ITEM_APPLE == x.incomingData("apple"))
            System.out.println("ITEM_APPLE");
    }
    }
}

You just have to ensure the string value's hash codes does not clash ;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文