Arrays.Aslist(Int[]) Not Working

Arrays.asList(int[]) not working

When you pass an array of primitives (int[] in your case) to Arrays.asList, it creates a List<int[]> with a single element - the array itself. Therefore contains(3) returns false. contains(array) would return true.

If you'll use Integer[] instead of int[], it will work.

Integer[] array = {3, 2, 5, 4};

if (Arrays.asList(array).contains(3))
{
System.out.println("The array contains 3");
}

A further explanation :

The signature of asList is List<T> asList(T...). A primitive can't replace a generic type parameter. Therefore, when you pass to this method an int[], the entire int[] array replaces T and you get a List<int[]>. On the other hand, when you pass an Integer[] to that method, Integer replaces T and you get a List<Integer>.

Arrays.asList() not working as it should?

How about this?

Integer[] ints = new Integer[] {1,2,3,4,5};
List<Integer> list = Arrays.asList(ints);

Arrays.asList(arrayname).contains(int) doesnt work

Integer[] AllCards = {1,2,3,4,5,6,7,8,9,10};

if(Arrays.asList(AllCards).contains(1))
System.out.println("yes");
else {
System.out.println("no");
}

to understand why check this : https://stackoverflow.com/a/1467940/4088809

Using Arrays.asList with int array

List cannot hold primitive values because of java generics (see similar question). So when you call Arrays.asList(ar) the Arrays creates a list with exactly one item - the int array ar.

EDIT:

Result of Arrays.asList(ar) will be a List<int[]>, NOT List<int> and it will hold one item which is the array of ints:

[ [1,2,3,4,5] ]

You cannot access the primitive ints from the list itself. You would have to access it like this:

list.get(0).get(0) // returns 1
list.get(0).get(1) // returns 2
...

And I think that's not what you wanted.

How Arrays.asList(int[]) can return Listint[]?

There is no automatic autoboxing done of the underlying ints in Arrays.asList.

  • int[] is actually an object, not a primitive.

  • Here Arrays.asList(example) returns List<int[]>. List<int> is indeed invalid syntax.

  • You could use:

    List<Integer> exampleList = Arrays.asList(ArrayUtils.toObject(array));

    using Apache Commons ArrayUtils.

Arrays.asList(outer array).containsAll(Arrays.asList(inner array)) returns false when it shouldn't

Arrays.asList(), when passed a primitive array, produces a List whose single element is the input array. If you pass to it an Integer[] instead of int[], it will behave the way you expected.

Just change

    int[] digits = new int[chars.length];
for(int i = 0; i < chars.length; i++){
digits[i] = chars[i] - '0';
}
int[] allDigits = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};

to

    Integer[] digits = new Integer[chars.length];
for(int i = 0; i < chars.length; i++){
digits[i] = chars[i] - '0';
}
Integer[] allDigits = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9};


Related Topics



Leave a reply



Submit