How do i check if an Array List contains a certain

2019-07-25 15:08发布

问题:

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

    }

}

回答1:

you don't have to do this:

if(Arrays.asList(list).contains("Paul"))

because the identifier list is already an ArrayList

you'll need to do:

if(list.contains("Paul")){
    System.out.println("Yes it does");
}


回答2:

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]].

The correct solution for the problem already provided by '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");
 }


回答3:

ArrayList have their inbuilt function called contains(). So if you want to try with in built function you can simply use this method.

list.contains("Your_String")

This will return you boolean value true or false



标签: java oop