java 如何检查数组列表是否包含某个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43358590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i check if an Array List contains a certain string
提问by papa
I've looked on here and what i got did not really work. Here is the code which runs but it's not doing what i expect it to do
我看过这里,但我得到的并没有真正起作用。这是运行的代码,但它没有做我期望它做的事情
package bcu.gui;
import java.util.ArrayList;
import java.util.Arrays;
public class compare {
private static ArrayList<String> list = new ArrayList<String>();
public static void main(String[] args) {
list.add("Paul");
list.add("James");
System.out.println(list); // Printing out the list
// If the list containsthe name Paul, then print this. It still doesn't print even though paul is in the list
if(Arrays.asList(list).contains("Paul")){
System.out.println("Yes it does");
}
}
}
回答by Ousmane D.
you don't have to do this:
你不必这样做:
if(Arrays.asList(list).contains("Paul"))
because the identifier list
is already an ArrayList
因为标识符list
已经是ArrayList
you'll need to do:
你需要做:
if(list.contains("Paul")){
System.out.println("Yes it does");
}
回答by Mikhail Chibel
The reason why you not getting what you expected is the usage of
你没有得到你期望的原因是使用
Arrays.asList(list)
which returns a new array with a single element of type array. If your list contains two elements [Paul, James], then the Arrays.asList(list) will be [[Paul, James]].
它返回一个具有数组类型的单个元素的新数组。如果您的列表包含两个元素 [Paul, James],则 Arrays.asList(list) 将是 [[Paul, James]]。
The correct solution for the problem already provided by 'Ousmane Mahy Diaw'
'Ousmane Mahy Diaw' 已经提供的问题的正确解决方案
The following will also work for you:
以下内容也适用于您:
// if you want to create a list in one line
if (Arrays.asList("Paul", "James").contains("Paul")) {
System.out.println("Yes it does");
}
// or if you want to use a copy of you list
if (new ArrayList<>(list).contains("Paul")) {
System.out.println("Yes it does");
}
回答by Rajesh Chaudhary
ArrayList have their inbuilt function called contains(). So if you want to try with in built function you can simply use this method.
ArrayList 有它们的内置函数,称为 contains()。所以如果你想尝试内置函数,你可以简单地使用这个方法。
list.contains("Your_String")
list.contains("Your_String")
This will return you boolean value true or false
这将返回布尔值 true 或 false