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

后端 未结 29 2816
予麋鹿
予麋鹿 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:52

    Actually, if you use HashSet as Tom Hawtin proposed you don't need to worry about sorting, and your speed is the same as with binary search on a presorted array, probably even faster.

    It all depends on how your code is set up, obviously, but from where I stand, the order would be:

    On an unsorted array:

    1. HashSet
    2. asList
    3. sort & binary

    On a sorted array:

    1. HashSet
    2. Binary
    3. asList

    So either way, HashSet for the win.

提交回复
热议问题