Home » Java » java – Arrays.asList returns false-Exceptionshub

java – Arrays.asList returns false-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I just wanna check if my String[] array contains “n” or “s”.

String[] coordinatesExample = {"57.8136°s", "28.3496°e"};

private void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }

So I expected: “It works!”, but
in fact: “RAKAMAKAFO”

What I did wrong?

How to&Answers:

Your current solution only works if you have a String Array like this:

String[] coordinatesExample = {"57.8136°s", "28.3496°e", "s"};

Try this if you want to check if any String from your Array contains “n” or “s”.

private static void isContains(String[] coordinates) {
    boolean contains = Arrays.stream(coordinates)
            .anyMatch(coordinate -> coordinate.contains("s") || coordinate.contains("n"));
    if (contains) {
        System.out.println("It works!");
    } else {
        System.out.println("RAKAMAKAFO");
    }
}

Answer:

When you do Arrays.asList(coordinates) you get the list containing two items: 57.8136°s and 28.3496°e. So using .contains("s") you test if any of your items is “s” which is obviously not the case.

Answer:

Contains only checks to see if the list contains one of the elements which s is not one.

From the JavaDoc for the List interface

boolean contains​(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that Objects.equals(o, e).

If you did the following, it would return print It works! because the first string in the list contained an s

private static void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).get(0).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }
    }
}