我有一个String[],其值如下:

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

给定字符串s,是否有一种测试VALUES是否包含s的好方法?


当前回答

可以使用Arrays类对值执行二进制搜索。如果数组未排序,则必须使用同一类中的排序函数对数组进行排序,然后对其进行搜索。

其他回答

如果数组未排序,则必须遍历所有内容,并对每个内容调用equals。

如果数组已排序,则可以执行二进制搜索,Arrays类中有一个。

一般来说,如果要进行大量的成员身份检查,您可能希望将所有内容存储在集合中,而不是存储在数组中。

在下面使用-

    String[] values = {"AB","BC","CD","AE"};
    String s = "A";
    boolean contains = Arrays.stream(values).anyMatch(v -> v.contains(s));

你可以用两种方法检查

A) 通过将数组转换为字符串,然后通过.incontains方法检查所需的字符串

String a = Arrays.toString(VALUES);
System.out.println(a.contains("AB"));
System.out.println(a.contains("BC"));
System.out.println(a.contains("CD"));
System.out.println(a.contains("AE"));

B) 这是一种更有效的方法

Scanner s = new Scanner(System.in);

String u = s.next();
boolean d = true;
for (int i = 0; i < VAL.length; i++) {
    if (VAL[i].equals(u) == d)
        System.out.println(VAL[i] + " " + u + VAL[i].equals(u));
}

使用以下方法(在本代码中contains()方法是ArrayUtils.in()):

对象Utils.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);
    }
}

阵列应用程序.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 <T> 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 <T> 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 <T> boolean in(final T[] ts, final T t) {
        return indexOf(ts, t) > -1;
    }
}

正如您在上面的代码中看到的,还有其他实用方法ObjectUtils.equals()和ArrayUtils.indexOf(),它们也在其他地方使用。

如果你有谷歌收藏库,Tom的答案可以通过使用ImmutableSet简化很多(http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)

这确实消除了初始化过程中的大量混乱

private static final Set<String> VALUES =  ImmutableSet.of("AB","BC","CD","AE");