当前位置: 移动技术网 > IT编程>开发语言>Java > 个人笔记(一)正确使用equals方法

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

2020年07月12日  | 移动技术网IT编程  | 我要评论

使用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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网