如何确定数组是否包含Java中的特定值?我有一个String[]具有这样的价值:public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};给出String s,有没有一个好的方法来测试VALUES含s?
4 回答
12345678_0001
TA贡献1802条经验 获得超5个赞
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};new String[];
private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
new String[] {"AB","BC","CD","AE"}));Collections.unmodifiableSet
VALUES.contains(s)
最新情况:Set.of.
private static final Set<String> VALUES = Set.of( "AB","BC","CD","AE");
三国纷争
TA贡献1804条经验 获得超7个赞
ArrayUtils.contains
public static boolean contains(Object[] array, Object objectToFind)
falsenull.
例子:
String[] fieldsToInclude = { "id", "name", "location" };if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
// Do some stuff.}
慕雪6442864
TA贡献1812条经验 获得超5个赞
public static <T> boolean contains(final T[] array, final T v) {
for (final T e : array)
if (e == v || v != null && v.equals(e))
return true;
return false;}改进:
v != nullarrayforcontains()
public static <T> boolean contains2(final T[] array, final T v) {
if (v == null) {
for (final T e : array)
if (e == null)
return true;
}
else {
for (final T e : array)
if (e == v || v.equals(e))
return true;
}
return false;}添加回答
举报
0/150
提交
取消
