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

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

    Use the following (the contains() method is ArrayUtils.in() in this code):

    ObjectUtils.java

    public class ObjectUtils{
    
        /**
         * A null safe method to detect if two objects are equal.
         * @param object1
         * @param object2
         * @return true if either both objects are null, or equal, else returns false.
         */
        public static boolean equals(Object object1, Object object2){
            return object1==null ? object2==null : object1.equals(object2);
        }
    
    }
    

    ArrayUtils.java

    public class ArrayUtils{
    
        /**
         * Find the index of of an object is in given array, starting from given inclusive index.
         * @param ts  Array to be searched in.
         * @param t  Object to be searched.
         * @param start  The index from where the search must start.
         * @return Index of the given object in the array if it is there, else -1.
         */
        public static  int indexOf(final T[] ts, final T t, int start){
            for(int i = start; i < ts.length; ++i)
                if(ObjectUtils.equals(ts[i], t))
                    return i;
            return -1;
        }
    
        /**
         * Find the index of of an object is in given array, starting from 0;
         * @param ts  Array to be searched in.
         * @param t  Object to be searched.
         * @return  indexOf(ts, t, 0)
         */
        public static  int indexOf(final T[] ts, final T t){
            return indexOf(ts, t, 0);
        }
    
        /**
         * Detect if the given object is in the given array.
         * @param ts  Array to be searched in.
         * @param t  Object to be searched.
         * @return  If indexOf(ts, t) is greater than -1.
         */
        public static  boolean in(final T[] ts, final T t){
            return indexOf(ts, t) > -1 ;
        }
    
    }
    

    As you can see in the code above, that there are other utility methods ObjectUtils.equals() and ArrayUtils.indexOf(), that were used at other places as well.

提交回复
热议问题