Tutorial :Arrays.contains(int) error



Question:

can i ask why does the following output 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");          }        }    }  

Thanks!


Solution:1

The asList method here returns a List<int[]>, which is not what you expect.

The reason is that you can't have a List<int>. In order to achieve what you want, make an array of Integer - Integer[].

Apache commons-lang has ArrayUtils for that:

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

or make the array initially Integer[] so that no conversion is needed


Solution:2

Arrays.asList returns a generic type. int is a primitive type.

Change the type of your array from int to Integer:

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


Solution:3

Because Arrays.asList(VOWEL_POS) constructs a List<int[]> and not a List<Integer>. There is no List<int> in Java (or of any other primitive type).

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


Solution:4

Som info here

I think the problem will be that the List contains only a single item, that is actually an integer array.

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »