我有一个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");
}
其他回答
如果数组未排序,则必须遍历所有内容,并对每个内容调用equals。
如果数组已排序,则可以执行二进制搜索,Arrays类中有一个。
一般来说,如果要进行大量的成员身份检查,您可能希望将所有内容存储在集合中,而不是存储在数组中。
开发人员通常会:
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
上面的代码可以工作,但不需要先将列表转换为set。将列表转换为集合需要额外的时间。它可以简单到:
Arrays.asList(arr).contains(targetValue);
or
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;
第一个比第二个更可读。
Java SE 9的简明更新
引用数组不正确。对于这种情况,我们需要一套。从Java SE 9开始,我们有Set.of。
private static final Set<String> VALUES = Set.of(
"AB","BC","CD","AE"
);
“给定字符串s,是否有测试VALUES是否包含s的好方法?”
VALUES.contains(s)
O(1)。
正确的类型,不可变,O(1)和简洁。漂亮*
原始答案详细信息
只是为了先清除代码。我们已(更正):
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
这是一个可变的静态,FindBugs会告诉你这是非常顽皮的。不要修改静态,也不要允许其他代码这样做。至少,该字段应该是私有的:
private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
(注意,实际上可以删除新的String[];位。)
引用数组仍然不好,我们需要一个集合:
private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
new String[] {"AB","BC","CD","AE"}
));
(偏执狂的人,比如我自己,如果这是用Collections.unmodifiedSet包装的话,可能会更放心——然后甚至可以公开。)
(*在品牌方面,集合API仍然可以预见地缺少不可变的集合类型,语法对于我的口味来说仍然过于冗长。)
事实上,如果按照Tom Hawtin的建议使用HashSet<String>,您就不必担心排序问题,而且您的速度与对预排序数组进行二进制搜索的速度相同,甚至可能更快。
显然,这取决于代码的设置方式,但从我的立场来看,顺序应该是:
在未排序的数组上:
哈希集as列表排序二进制(&B)
在排序数组上:
哈希集二进制的as列表
所以不管怎样,HashSet都会获胜。
检查此项
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
}
}