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

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

    1. For arrays of limited length use the following (as given by camickr). This is slow for repeated checks, especially for longer arrays (linear search).

       Arrays.asList(...).contains(...)
      
    2. For fast performance if you repeatedly check against a larger set of elements

      • An array is the wrong structure. Use a TreeSet and add each element to it. It sorts elements and has a fast exist() method (binary search).

      • If the elements implement Comparable & you want the TreeSet sorted accordingly:

        ElementClass.compareTo() method must be compatable with ElementClass.equals(): see Triads not showing up to fight? (Java Set missing an item)

        TreeSet myElements = new TreeSet();
        
        // Do this for each element (implementing *Comparable*)
        myElements.add(nextElement);
        
        // *Alternatively*, if an array is forceably provided from other code:
        myElements.addAll(Arrays.asList(myArray));
        
      • Otherwise, use your own Comparator:

        class MyComparator implements Comparator {
             int compareTo(ElementClass element1; ElementClass element2) {
                  // Your comparison of elements
                  // Should be consistent with object equality
             }
        
             boolean equals(Object otherComparator) {
                  // Your equality of comparators
             }
        }
        
        
        // construct TreeSet with the comparator
        TreeSet myElements = new TreeSet(new MyComparator());
        
        // Do this for each element (implementing *Comparable*)
        myElements.add(nextElement);
        
      • The payoff: check existence of some element:

        // Fast binary search through sorted elements (performance ~ log(size)):
        boolean containsElement = myElements.exists(someElement);
        

提交回复
热议问题