zoukankan      html  css  js  c++  java
  • java判断两个对象是否相同个方法源码分析

    1,错误用法

    a.equals(b)  //a 是null, 抛出NullPointException异常
    

      

    2,正确用法

    Objects.equals(a, b)   //这种方法对null值进行了条件判断
    

      分析源码

    public final class Objects {  
        private Objects() {  
            throw new AssertionError("No java.util.Objects instances for you!");  
        }  
       
        public static boolean equals(Object a, Object b) {  
            return (a == b) || (a != null && a.equals(b));  //null值先通过地址判断
        }  
    

      

    public boolean equals(Object anObject) {
            if (this == anObject) {
                return true;
            }
            if (anObject instanceof String) {
                String anotherString = (String)anObject;
                int n = value.length;
                if (n == anotherString.value.length) {
                    char v1[] = value;
                    char v2[] = anotherString.value;
                    int i = 0;
                    while (n-- != 0) {
                        if (v1[i] != v2[i])
                            return false;
                        i++;
                    }
                    return true;
                }
            }
            return false;
        }
    

      

  • 相关阅读:
    内置函数(少量)
    画国旗(尺寸不标准)
    测试题——程序
    乱码笔记2--字典
    列表
    课堂笔记 ——————乱
    如何利用pip安装国内镜像源
    pip常用指令
    pip卸载
    pip简介
  • 原文地址:https://www.cnblogs.com/torchstar/p/14865790.html
Copyright © 2011-2022 走看看