Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Arrays.asList(...).contains(...) works?

I have the following code..

    String[] weekEnds={"0","6"};

    for(int i=0;i<7;i++){

    if(Arrays.asList(weekEnds).contains(i)){

     System.out.println("I am in the array");       
    }    
  }

but its not going into the if condition ..i dont know where im going wrong.. Thanks in Advance..

like image 906
Kabilan S Avatar asked Jun 11 '12 12:06

Kabilan S


People also ask

How to declare an array aslist in Java?

There are two ways to declare a list using the java Arrays asList method The first method is to declare an array and then use the java Arrays.asList method. Explained in the code below Another method can be passing the array elements as an argument to the java Arrays.asList method.

Why is arrays aslist () used?

Why is Arrays.asList () used? If you have an Array that you need to turn into a list then java.util.Arrays provides a wrapper Arrays.asList () to serve this purpose. In simple words, this method takes an array as a parameter and returns a list. Major portions of the Java platform API were developed before the collections framework was introduced.

What is the syntax of the contains () method of ArrayList?

The syntax of the contains () method is: Here, arraylist is an object of the ArrayList class. The contains () method takes a single parameter. returns true if the specified element is present in the arraylist. returns false if the specified element is not present in the arraylist.

Which method can be used to pass an array to list?

As you can see both the methods declare the same output, it is optional whether which method can be used to pass the array in the java Arrays.asList () method. In the java Arrays.asList () method, if another array is set in the old list, the updated list will have the latest array passed to it.


2 Answers

Either change the if condition to

if(Arrays.asList(weekEnds).contains(String.valueOf(i))){

Or change your array to

Integer[] weekEnds={0,6};
like image 112
adarshr Avatar answered Oct 25 '22 05:10

adarshr


You're comparing Strings and ints. Your array contains Strings ("0", "6"), but you're passing an int into the comparison.

That int will be boxed to an Integer, but an Integer(1) does not equal "1"

like image 29
Brian Agnew Avatar answered Oct 25 '22 04:10

Brian Agnew