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

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

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


当前回答

检查此项

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
    }
}

其他回答

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

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

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

在Java 8中,使用Streams。

List<String> myList =
        Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList.stream()
        .filter(s -> s.startsWith("c"))
        .map(String::toUpperCase)
        .sorted()
        .forEach(System.out::println);

一种可能的解决方案:

import java.util.Arrays;
import java.util.List;

public class ArrayContainsElement {
  public static final List<String> VALUES = Arrays.asList("AB", "BC", "CD", "AE");

  public static void main(String args[]) {

      if (VALUES.contains("AB")) {
          System.out.println("Contains");
      } else {
          System.out.println("Not contains");
      }
  }
}

事实上,如果按照Tom Hawtin的建议使用HashSet<String>,您就不必担心排序问题,而且您的速度与对预排序数组进行二进制搜索的速度相同,甚至可能更快。

显然,这取决于代码的设置方式,但从我的立场来看,顺序应该是:

在未排序的数组上:

哈希集as列表排序二进制(&B)

在排序数组上:

哈希集二进制的as列表

所以不管怎样,HashSet都会获胜。

使用简单的循环是最有效的方法。

boolean useLoop(String[] arr, String targetValue) {
    for(String s: arr){
        if(s.equals(targetValue))
            return true;
    }
    return false;
}

由Programcreek提供