Java null.equals(object o)

2020-03-01 03:07发布

I know it's not possible to call the equals method on a null object like that:

//NOT WORKING
            String s1 = null;
            String s2 = null;
            if(s1.equals(s2))
            {
                System.out.println("NOT WORKING :'(");
            }

But in my case I want to compare two objects from two database and these two objects can have attributes null...

So what is the method to compare two attributes, knowing that we are not sure that the value is null or filled.

This method is good or not ?

//WORKING
            String s1 = "test";
            String s2 = "test";
            if(s1 == s2 || s1.equals(s2))
            {
                System.out.println("WORKING :)");
            }

            //WORKING
            String s1 = null;
            String s2 = null;
            if(s1 == s2 || s1.equals(s2))
            {
                System.out.println("WORKING :)");
            }

I'm not sure because in this case it's not working ... :

//NOT WORKING
            String s1 = null;
            String s2 = null;
            if(s1.equals(s2)|| s1 == s2  )
            {
                System.out.println("NOT WORKING :'''(");
            }

标签: java object null
9条回答
劳资没心,怎么记你
2楼-- · 2020-03-01 04:05

You will need to check atleast one is not null before doing equals method -

if(s1 == s2 || (s1!=null && s1.equals(s2)))  {
   System.out.println("WORKING :)");
} 

here s1==s2 will work incase of null==null . But if even one is not null, then you need to check atleast s1 before doing equals.

Update: As edited by @'bernard paulus', if you are using Java 7, you can use java.util.Objects.equals(Object, Object)

查看更多
放我归山
3楼-- · 2020-03-01 04:05

I think you are comparing two objects.

So it should be like this

if(s1==null & s2 == null)  // both null but equal
   return true;
else if(s1 != null && s2 != null && s1.equals(s2)) // both not null and equal
   return true;
else
   return false;

True - for equal False - for not equal

查看更多
神经病院院长
4楼-- · 2020-03-01 04:07

If you want to know if something is 'null' you can compare using:

if(s1==null)

If it is null it will tell you true. Problem, if you have a String that is null, you can't use the methods equals(). For this reason your third part doesn't work, because if it is equals you can't use a null pointer.

You should check first if the object is null and then if it isn't null use the methods equals.

On the other hand be careful because maybe you want to compare the empty String, in this case you have to use equal(""). If you want to compare the empty string, is better that you put first the empty string on this way:

"".equals(YourStringNotNull);

Sorry for my English I hope it helps you.

查看更多
登录 后发表回答