我有一个String[],其值如下:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
给定字符串s,是否有一种测试VALUES是否包含s的好方法?
我有一个String[],其值如下:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
给定字符串s,是否有一种测试VALUES是否包含s的好方法?
当前回答
试试看:
ArrayList<Integer> arrlist = new ArrayList<Integer>(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
boolean retval = arrlist.contains(10);
if (retval == true) {
System.out.println("10 is contained in the list");
}
else {
System.out.println("10 is not contained in the list");
}
其他回答
只需手动执行即可:
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!=null条件在方法中是常量。在方法调用期间,它始终计算为相同的布尔值。因此,如果输入数组很大,只计算一次这个条件会更有效,我们可以根据结果在for循环中使用简化/更快的条件。改进的contains()方法:
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;
}
事实上,如果按照Tom Hawtin的建议使用HashSet<String>,您就不必担心排序问题,而且您的速度与对预排序数组进行二进制搜索的速度相同,甚至可能更快。
显然,这取决于代码的设置方式,但从我的立场来看,顺序应该是:
在未排序的数组上:
哈希集as列表排序二进制(&B)
在排序数组上:
哈希集二进制的as列表
所以不管怎样,HashSet都会获胜。
ObStupidAnswer(但我认为这里有一个教训):
enum Values {
AB, BC, CD, AE
}
try {
Values.valueOf(s);
return true;
} catch (IllegalArgumentException exc) {
return false;
}
Arrays.asList(yourArray).contains(yourValue)
警告:这对基元数组无效(请参见注释)。
从java-8开始,您现在可以使用Streams。
String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);
要检查int、double或long数组是否包含值,请分别使用IntStream、DoubleStream或LongStream。
实例
int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
检查此项
String[] VALUES = new String[]{"AB", "BC", "CD", "AE"};
String s;
for (int i = 0; i < VALUES.length; i++) {
if (VALUES[i].equals(s)) {
// do your stuff
} else {
//do your stuff
}
}