Objects类的的equals方法

Objects类的equals方法:

对两个对象进行比较,防止空指针异常NullPointerException

public static boolean equals(Object a, Object b) {
     eturn (a == b) || (a != null && a.equals(b));
     }

代码如下:

package com.object.demo01;

import java.sql.SQLOutput;
import java.util.Objects;

public class Demo03Objects {
    public static void main(String[] args) {
//        String s1 = "abc";
        String s1 = null;

        String s2 = "aaa";

//        boolean b = s1.equals(s2);   //NullPointerException是不能调用方法的,会抛出空指针异常
//        System.out.println(b); //false ---NullPointerException

/*
       Objects类的equals方法:对两个对象进行比较,防止空指针异常NullPointerException
       public static boolean equals(Object a, Object b) {
            return (a == b) || (a != null && a.equals(b));
        }
 */
        boolean b2 = Objects.equals(s1, s2);
        System.out.println(b2);  //false
    }
}

你可能感兴趣的:(Objects类的的equals方法)