欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

个人笔记(一)正确使用equals方法

程序员文章站 2022-11-30 15:51:13
public static void main(String[] args) {String str = null;if (str.equals("今天星期六")){//Exception in thread "main" java.lang.NullPointerExceptionSystem.out.println(true);}else {System.out.println(false);}}public static void main(String[...

使用equals方法的三种情况:

第一种:

public static void main(String[] args) {
		String str = null;
		if (str.equals("今天星期六")){//Exception in thread "main" java.lang.NullPointerException
			System.out.println(true);
		}else {
			System.out.println(false);
		}
}

第二种:

public static void main(String[] args) {
        String str = null;
        if (("今天星期六".equals(str))){
            System.out.println(true);
        }else {
            System.out.println(false);//false
        }
}

第三种:(推荐使用)

public static void main(String[] args) {
//        String str = null;
        if ((Objects.equals(null,"今天星期六"))){//java.util.Objects#equals(JDK7 引入的工具类)
            System.out.println(true);
        }else {
            System.out.println(false);//false
        }
}

源码分析:

	/**
     * Returns {@code true} if the arguments are equal to each other
     * and {@code false} otherwise.
     * Consequently, if both arguments are {@code null}, {@code true}
     * is returned and if exactly one argument is {@code null}, {@code
     * false} is returned.  Otherwise, equality is determined by using
     * the {@link Object#equals equals} method of the first
     * argument.
     *
     * @param a an object
     * @param b an object to be compared with {@code a} for equality
     * @return {@code true} if the arguments are equal to each other
     * and {@code false} otherwise
     * @see Object#equals(Object)
     */
    public static boolean equals(Object a, Object b) {//源码
        return (a == b) || (a != null && a.equals(b));
    }

本文地址:https://blog.csdn.net/qq_38258824/article/details/107289959