Arrays.contains (int) error

May I ask why the following output is FALSE?

import java.util.Arrays;


public class Test2 {

    public static void main(String[] args) {
        new Test2();
    }

    private final int[] VOWEL_POS = {0,4,8,14,20};

    Test2(){
        if(Arrays.asList(VOWEL_POS).contains(0)){
            System.out.print("TRUE");
        }else{
            System.out.print("FALSE");
        }

    }

}

Thank!

+3
source share
4 answers

In this case, the method asListreturns List<int[]>what you are not expecting.

The reason is that you cannot have List<int>. To achieve what you want, create an array Integer- Integer[].

Apache commons-lang has ArrayUtilsfor this:

if(Arrays.asList(ArrayUtils.toObject(VOWEL_POS)).contains(0))

or make an array first Integer[]so that no conversion is required

+8
source

Arrays.asListreturns a generic type. intis a primitive type.

Change the array type from intto Integer:

private final Integer[] VOWEL_POS = {0,4,8,14,20};
+2
source

Because it Arrays.asList(VOWEL_POS)builds a List<int[]>, not a List<Integer>. In Java (or any other primitive type) no List<int>.

Just change your definition to private final Integer[] VOWEL_POS = {0,4,8,1,20};, and it will become List<Integer>.

+2
source

Som info here

I think the problem is that List contains only one element, which is actually an integer array.

Since int is a primitive type, you do not call the asList (Object []) method, but the varargs asList (T ... a) method.

+1
source

Source: https://habr.com/ru/post/1754973/


All Articles