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

Java中关于equals与==在判断空null时的不同

程序员文章站 2022-06-21 14:21:25
先看代码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 ne...

先看代码

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)?false

test2:
pnull equals pnull2: pnull == pnull2?false
pnull.equals(pnull2)?true
Objects.equals(pnull,pnull2)?true

test3:
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