How do I determine whether an array contains a particular value in Java?

后端 未结 29 2579
予麋鹿
予麋鹿 2020-11-21 05:00

I have a String[] with values like so:

public static final String[] VALUES = new String[] {\"AB\",\"BC\",\"CD\",\"AE\"};

Given

29条回答
  •  有刺的猬
    2020-11-21 05:49

    Concise update for Java SE 9

    Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of.

    private static final Set VALUES = Set.of(
        "AB","BC","CD","AE"
    );
    

    "Given String s, is there a good way of testing whether VALUES contains s?"

    VALUES.contains(s)
    

    O(1).

    The right type, immutable, O(1) and concise. Beautiful.*

    Original answer details

    Just to clear the code up to start with. We have (corrected):

    public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
    

    This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:

    private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
    

    (Note, you can actually drop the new String[]; bit.)

    Reference arrays are still bad and we want a set:

    private static final Set VALUES = new HashSet(Arrays.asList(
         new String[] {"AB","BC","CD","AE"}
    ));
    

    (Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could then even be made public.)

    (*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.)

提交回复
热议问题