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

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

    Arrays.asList() -> then calling the contains() method will always work, but a search algorithm is much better since you don't need to create a lightweight list wrapper around the array, which is what Arrays.asList() does.

    public boolean findString(String[] strings, String desired){
       for (String str : strings){
           if (desired.equals(str)) {
               return true;
           }
       }
       return false; //if we get here… there is no desired String, return false.
    }
    

提交回复
热议问题