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

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

    Four Different Ways to Check If an Array Contains a Value

    1. Using List:

      public static boolean useList(String[] arr, String targetValue) {
          return Arrays.asList(arr).contains(targetValue);
      }
      
    2. Using Set:

      public static boolean useSet(String[] arr, String targetValue) {
          Set set = new HashSet(Arrays.asList(arr));
          return set.contains(targetValue);
      }
      
    3. Using a simple loop:

      public static boolean useLoop(String[] arr, String targetValue) {
          for (String s: arr) {
              if (s.equals(targetValue))
                  return true;
          }
          return false;
      }
      
    4. Using Arrays.binarySearch():

      The code below is wrong, it is listed here for completeness. binarySearch() can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted.

      public static boolean binarySearch(String[] arr, String targetValue) {  
          return Arrays.binarySearch(arr, targetValue) >= 0;
      }
      

    Quick Example:

    String testValue="test";
    String newValueNotInList="newValue";
    String[] valueArray = { "this", "is", "java" , "test" };
    Arrays.asList(valueArray).contains(testValue); // returns true
    Arrays.asList(valueArray).contains(newValueNotInList); // returns false
    

提交回复
热议问题