3

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!

Dori
  • 18,283
  • 17
  • 74
  • 116
  • See also this Java Puzzler: http://tech.puredanger.com/2007/03/27/array-puzzler/ and this related SO question: http://stackoverflow.com/questions/1467913/arrays-aslist-not-working-as-it-should – Christian Semrau Jul 16 '10 at 11:14

4 Answers4

8

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
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};
Noel M
  • 15,812
  • 8
  • 39
  • 47
2

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>.

Robert Petermeier
  • 4,122
  • 4
  • 29
  • 37
1

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.

sje397
  • 41,293
  • 8
  • 87
  • 103