我有一个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
    }
}

其他回答

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仍然可以预见地缺少不可变的集合类型,语法对于我的口味来说仍然过于冗长。)

Arrays.asList()->然后调用contains()方法将始终有效,但搜索算法要好得多,因为不需要在数组周围创建轻量级列表包装器,这就是Arrays.as list()所做的。

public boolean findString(String[] strings, String desired){
   for (String str : strings){
       if (desired.equals(str)) {
           return true;
       }
   }
   return false; //if we get here… there is no desired String, return false.
}

在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);

试试看:

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");
}

一种可能的解决方案:

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");
      }
  }
}