[英]How do i check if an Array List contains a certain string
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");
}
}
}
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");
}
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. 它返回一个包含array类型的单个元素的新数组。 If your list contains two elements [Paul, James], then the Arrays.asList(list) will be [[Paul, James]].
如果你的列表包含两个元素[Paul,James],那么Arrays.asList(列表)将是[[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");
}
ArrayList have their inbuilt function called contains(). ArrayList有自己的内置函数contains()。 So if you want to try with in built function you can simply use this method.
因此,如果您想尝试使用内置函数,您只需使用此方法即可。
list.contains("Your_String") list.contains( “Your_String”)
This will return you boolean value true or false 这将返回布尔值true或false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.