Finding needle in a haystack (error when comparing two objects with .equals)

coco :

Trying to find a string "needle" in an Object array. But using .equals to compare gives me an error. But using == works. Why? I thought I had to use .equals to compare objects/strings.

Code that runs with ==

public class ANeedleInTheHaystack_8 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Object[] haystack2 = {"283497238987234", "a dog", "a cat", "some random junk", "a piece of hay", "needle", "something somebody lost a while ago"};
        Object[] haystack1 = {"3", "123124234", null, "needle", "world", "hay", 2, "3", true, false};
        System.out.println(findNeedle(haystack2));
        System.out.println(findNeedle(haystack1));
    }

    public static String findNeedle(Object[] haystack) {

        for(int i = 0 ; i < haystack.length ; i ++) {
            if(haystack[i] == "needle") {
                return String.format("found the needle at position %s", i);
            }
        }
        return null;
    }

}

Out put

found the needle at position 5
found the needle at position 3

and code that doesn't run with .equals

public class ANeedleInTheHaystack_8 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Object[] haystack2 = { "283497238987234", "a dog", "a cat", "some random junk", "a piece of hay", "needle",
                "something somebody lost a while ago" };
        Object[] haystack1 = { "3", "123124234", null, "needle", "world", "hay", 2, "3", true, false };
        System.out.println(findNeedle(haystack2));
        System.out.println(findNeedle(haystack1));
    }

    public static String findNeedle(Object[] haystack) {
        for(int i = 0 ; i < haystack.length ; i ++) {
            if(haystack[i].equals("needle")) {
                return String.format("found the needle at position %s", i);
            }
        }
        return null;
    }

}

out put

found the needle at position 5
Exception in thread "main" java.lang.NullPointerException
    at ANeedleInTheHaystack_8.findNeedle(ANeedleInTheHaystack_8.java:15)
    at ANeedleInTheHaystack_8.main(ANeedleInTheHaystack_8.java:10)

Seems like I am only getting an error when I am comparing with null. Can .equals compare an object with null?

William Nardo :

Change your method findNeedle like this:

    public static String findNeedle(Object[] haystack) {
        for(int i = 0 ; i < haystack.length ; i ++) {
            if("needle".equals(haystack[i])) {
                return String.format("found the needle at position %s", i);
            }
        }
        return null;
    }

You can't call method of null, but equals method can check if a object is equal to null.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=153880&siteId=1