1.效率最高(最原始)
代码如下(示例):
public class Demo {
public static boolean useLoop(String[] arr, String targetValue) {
for (String s : arr) {
if (s.equals(targetValue)) return true;
}
return false;
}
public static void main(String[] args) {
String arr[] = {"aa", "bb", "cc"};
String targetValue = "bb";
System.out.println(useLoop(arr, targetValue));
}
}文章来源:https://www.toymoban.com/news/detail-677044.html
运行结果:
2.List数组Contains
代码如下(示例):
import java.util.Arrays;
public class Demo {
public static boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
public static void main(String[] args) {
String arr[] = {"aa", "bb", "cc"};
String targetValue = "bb";
System.out.println(useList(arr, targetValue));
}
}
运行结果:
3.Set的Contains
代码如下(示例):
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
public static boolean useSet(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}
public static void main(String[] args) {
String arr[] = {"aa", "bb", "cc"};
String targetValue = "bb";
System.out.println(useSet(arr, targetValue));
}
}
运行结果:
4.Arrays的binarySearch
代码如下(示例):
import java.util.Arrays;
public class Demo {
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if (a > 0) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
String arr[] = {"aa", "bb", "cc"};
String targetValue = "bb";
System.out.println(useArraysBinarySearch(arr, targetValue));
}
}
运行结果:
文章来源地址https://www.toymoban.com/news/detail-677044.html
到了这里,关于java判断某个字符串是否在字符串数组中的方法(4种)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!