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

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

    Developers often do:

    Set set = new HashSet(Arrays.asList(arr));
    return set.contains(targetValue);
    

    The above code works, but there is no need to convert a list to set first. Converting a list to a set requires extra time. It can as simple as:

    Arrays.asList(arr).contains(targetValue);
    

    or

       for(String s: arr){
            if(s.equals(targetValue))
                return true;
        }
    
    return false;
    

    The first one is more readable than the second one.

提交回复
热议问题