Home  >  Article  >  Java  >  Java determines whether an array contains a certain value

Java determines whether an array contains a certain value

angryTom
angryTomOriginal
2019-11-14 09:20:176236browse

Java determines whether an array contains a certain value

java determines whether an array contains a certain value

I believe you often check when operating Java Does an array (unordered) contain a specific value? This is a frequently used and very useful operation in Java.

Four methods are given below. The most efficient one is the loop method. If you are interested, you can test it:

public boolean findStr(String[] args,String str){
        boolean result = false;
        //第一种:List
        result = Arrays.asList(args).contains(str);
        //第二种:set
        Set<String> sets = new HashSet<String>(Arrays.asList(args));
        result = sets.contains(str);
        //第三种:loop
        for (String s : args) {
            if (s.equals(str)){
                return true;
            }
        }
        //第四种:binarySearch(Arrays的binarySearch方法必须应用于有序数组)
        int res = Arrays.binarySearch(args, str);
        if (res > 0){
            return true;
        }
         
        return result;
}

The Arrays.binarySearch method has limitations and must be applied to ordered arrays. . It is recommended to use a loop to judge, which is highly efficient.

php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!

The above is the detailed content of Java determines whether an array contains a certain value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn