zoukankan      html  css  js  c++  java
  • Java中的比较== VS equals

    • Java中的泛型,不能支持基本数据类型(但是有包装类,也就是基本数据类型的类):boolean,byte,char,short,int,long,float,double

    只能是类对象

    • 包装类

      Boolean,Byte,Char,Short,Int,Long,Float,Double

    自动的解包和压包

    // 泛型数组 <== 曲线救国
    data = (E[])new Object[capacity];
    
    • equals VS ==

      1. ==

        基本数据类型比较的时候就是根据他们的来对比

        类对象来对比的时候是根据他们存储的地址来对比 (每一次new都是开辟新空间,有新的地址)

      2. equals

        默认情况和==相同,但是在一些类中重写了

        不过,我们可以根据情况自己重写该方法。一般重写都是自动生成,比较对象的成员变量值是否相同

        先看看String中被重写的equals(Tips:InteJ 在方法中调用equals,按Command+鼠标左键(windows中对应Ctrl+鼠标左键),直接进入String.java 并且定位到该方法

        
            /**
             * Compares this string to the specified object.  The result is {@code
             * true} if and only if the argument is not {@code null} and is a {@code
             * String} object that represents the same sequence of characters as this
             * object.
             *
             * @param  anObject
             *         The object to compare this {@code String} against
             *
             * @return  {@code true} if the given object represents a {@code String}
             *          equivalent to this string, {@code false} otherwise
             *
             * @see  #compareTo(String)
             * @see  #equalsIgnoreCase(String)
             */
            public boolean equals(Object anObject) {
              	// 默认引用同一个地址的对象返回true
                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;
            }
        

        所以就是 地址比较和内容比较的区别了(可以自己画个内存地址看看)

    慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!
  • 相关阅读:
    [SCOI2007]降雨量
    [SCOI2005]骑士精神
    LUOGU P1342 请柬
    spfa的复活
    Luogu P2396 yyy loves Maths VII
    Luogu P2801 教主的魔法
    HEOI2012 采花
    USACO05DEC Cleaning Shifts
    CF438D The Child and Sequence
    Codechef October Challenge 2019 Div.2
  • 原文地址:https://www.cnblogs.com/rookie123/p/14646509.html
Copyright © 2011-2022 走看看