java中==和equals

來源:互聯網
上載者:User

標籤:ringbuf   tostring   ==   自動   stringbu   rgs   字串   字元   system   

/** * @author zhaojiatao * @date 2018/7/19 */public class equalsLearn {    public static void main(String[] args) {        /**         * 當基本類型的比較時:只能用==,比較值;         * 當是參考型別比較時:如果未重寫equals方法,那麼equals用的是來自object類的equals方法,就是==,即比較記憶體位址         * 當是String類型時,如果是由String str="xxx";這樣直接賦值的話,比較的是字串的值;         *                 如果由String str=new String("xxx");方式new出來的對象的話,比較時是用的String類重寫的equals方法;         * 注意,toString方法返回的new String()對象;         *         */        int x=1;        int y=1;        // 基本類型判斷值是否相等        System.out.println(x==y);// true        //java會自動拆箱,由編譯器完成,實際上判斷的是x==1        System.out.println(x==new Integer(1));// true        //比較兩個對象的記憶體位址        System.out.println(new Integer(1)==new Integer(1));// false        //使用Integer封裝類重寫的equals方法比較        System.out.println(new Integer(1).equals(new Integer(1)));//true        String str1="abc";        String str2="abc";        // 比較兩個字串的值        System.out.println(str1==str2);// true        // 比較兩個字串 使用String類重寫的equeals方法        System.out.println(str1.equals(str2));// true        StringBuffer str3=new StringBuffer("efg");        StringBuffer str4=new StringBuffer("efg");        // 比較記憶體位址        System.out.println(str3==str4);//false        // 比較記憶體位址        System.out.println(str3.equals(str4));// false 由於StringBuffer類沒有重寫Object類的equals,故比較的是記憶體位址        // toString會產生new String()對象        System.out.println(str3.toString()==str4.toString());//false 比較記憶體位址        System.out.println(str3.toString().equals(str4.toString()));//true 使用String對象重寫的equals比較    }}

 

java中==和equals

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.