Java中关于equals与==在判断空null时的不同
先看代码
import java.awt.*; import java.util.Objects; /**This program demonstrates abstract classes
*/ public class PerTest { public static void main(String[] args) { Point pnull=new Point(); Point pnull2=new Point(); Point newnull=new Point(); newnull=null;//赋值 System.out.println("test1:\npnull equals null:"); System.out.println("pnull == null?"+(pnull==null)); System.out.println("pnull.equals(null)?"+pnull.equals(null)); System.out.println("Objects.equals(pnull,null)?"+ Objects.equals(pnull,null)); System.out.println("\ntest2:\npnull equals pnull2:"); System.out.println("pnull == pnull2?"+(pnull==pnull2)); System.out.println("pnull.equals(pnull2)?"+pnull.equals(pnull2)); System.out.println("Objects.equals(pnull,pnull2)?"+ Objects.equals(pnull,pnull2)); System.out.println("\ntest3:\npnull and pnull2 equals newnull:"); System.out.println("pnull == newnull?"+(pnull==newnull)); System.out.println("pnull2 == newnull?"+(pnull2==newnull)); System.out.println("pnull.equals(newnull)?"+pnull.equals(newnull)); System.out.println("pnull2.equals(newnull)?"+pnull2.equals(newnull)); System.out.println("Objects.equals(newnull,null)?"+ Objects.equals(newnull,null)); pnull=null; pnull2=null; System.out.println("test4:\npnull equals null after they both been assigned to null:"); System.out.println("pnull == null?"+(pnull==null)); System.out.println("pnull == pnull2?"+(pnull==pnull2)); //System.out.println("pnull.equals(null)?"+pnull.equals(null)); //报错,出现异常,没搞懂为什么 System.out.println("Objects.equals(pnull,null)?"+ Objects.equals(pnull,null)); } }
输出结果为:
test1:
pnull equals null: pnull == null?false
pnull.equals(null)?false
Objects.equals(pnull,null)?falsetest2:
pnull equals pnull2: pnull == pnull2?false
pnull.equals(pnull2)?true
Objects.equals(pnull,pnull2)?truetest3:
pnull and pnull2 equals newnull:
pnull == newnull?false
pnull2 == newnull?false
pnull.equals(newnull)?false
pnull2.equals(newnull)?false
Objects.equals(newnull,null)?true
test4:
pnull equals null after they both been assigned to null:
pnull == null?true
pnull == pnull2?true
Objects.equals(pnull,null)?true
本文地址:https://blog.csdn.net/qq_41135605/article/details/108864661
上一篇: JSP页面开发与用户如何进行交互使用
下一篇: (转)重述——迪米特法则