5

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

    }

}
3
  • 2
    Arrays.asList(list)? list is already a List...? Commented Apr 12, 2017 at 1:11
  • Arrays.asList(list) creates an object of type ArrayList<ArrayList<String>> Commented Apr 12, 2017 at 1:12
  • if(Arrays.asList(list).contains("Paul")){ should be if(list.contains("Paul")){ Commented Apr 12, 2017 at 1:13

3 Answers 3

9

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");
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.