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

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

    You can use ArrayUtils.contains from Apache Commons Lang

    public static boolean contains(Object[] array, Object objectToFind)

    Note that this method returns false if the passed array is null.

    There are also methods available for primitive arrays of all kinds.

    Example:

    String[] fieldsToInclude = { "id", "name", "location" };
    
    if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
        // Do some stuff.
    }
    

提交回复
热议问题