Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to determine whether a value exists in an array of String strings in java

Shulou Source: shulou.com Published: 2022-06-02 10:25:50 09月17日 Update

Today, I will talk to you about how to determine whether there is a certain value in the String string array in java. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Java determines whether a value exists in the String string array

There are two ways for java to determine whether a value exists in an array of String strings. You can use the binarySearch (Object [] a, Object key) method in the Arrays class to find out whether a value exists. If a value exists, the return value is greater than 0, and vice versa.

Advantages: the use of binary search method, fast and efficient. Cons: the array of queries must be ordered, and it is useless to use this method if not.

String [] array = {"1", "2", "3", "4"}; int index = Arryas.binarySearch (array, "2"); System.out.println ("index:" + index); / /-index:1index = Arryas.binarySearch (array, "0"); System.out.println ("index:" + index); / /-index:-1index = Arryas.binarySearch (array, "5"); System.out.println ("index:" + index); / /-index:-5

two。 Use the asList () method in the Arrays class to convert the array to a List () list, and use the contains () method to determine whether there is a value in the array

Advantages: arrays can be out of order and have no order requirements. Disadvantages: query efficiency may be a little slow, but it should not affect the overall situation.

String [] array = {"1", "2", "3", "4"}; boolean flag = Arrays.asList (array) .targets ("2"); System.out.println ("flag:" + flag); / /-- flag:trueflag = Arrays.asList (array) .targets ("0"); System.out.println ("flag:" + flag); / /-- flag:falseflag = Arrays.asList (array) .customers ("5"); System.out.println ("flag:" + flag) / /-flag:false

After reading the above, do you have any further understanding of how to determine whether there is a value in the String string array in java? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Array character string method content order advantage efficiency disadvantage query overall situation more useful this method knowledge article industry information channel order Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Microsoft Apple OPPO Reno Linux