-1

This code block prints "not contains" and i don't know why, can somebody help me ?

private static final int[] YEARS = new int[] {
        1881, 1893, 1900, 1910, 1919, 1923, 1930, 1932, 1934, 1938
};

public static void main(String[] args) {
    int year = 1919;
    System.out.println(YEARS);

    if (Arrays.asList(YEARS).contains(year))
    {
        System.out.println("Contains");
    }
    else {
        System.out.println("Not contains");
    }
    // Write your code here below
}

}

atılgan
  • 23
  • 8
  • Does this answer your question? [Arrays.asList() not working as it should?](https://stackoverflow.com/questions/1467913/arrays-aslist-not-working-as-it-should) – Chaosfire Nov 01 '22 at 08:39
  • Additionally, please fix question title, it has nothing in common with the actual question you are asking. – Chaosfire Nov 01 '22 at 08:40
  • 1
    there is no method `asList(int... )` (receiving primitive values), only `asList(T...)` and the generic type `T` cannot receive primitives, so it is creating a list with a single object, the whole (int) array itself || you can use `Arrays.binarySearch(int[], int)` if the array is sorted; or use `IntStream.of(YEARS).anyMatch(y -> y==1919)` – user16320675 Nov 01 '22 at 10:17

2 Answers2

1

that's because you are using int in your arraylist when you should be using Integer

int is a primitive type and doesn't work with Arraylist which requires a non-primitive type

change int to Integer and that code should work

Icarus
  • 501
  • 2
  • 16
1

Arrays.asList(YEARS) will result in a List<int[]>, you will not find a single int in there using the contains(int) method of a List

You probably expected a List<Integer>, which you can get by

List<Integer> years = Arrays.stream(YEARS).boxed().collect(Collectors.toList());

The resulting List<Integer> can be checked for the presence of a single int using the contains method because it is a list of integers contrary to the list of arrays of integers produced by Arrays.asList(YEARS).

deHaar
  • 17,687
  • 10
  • 38
  • 51