第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java null檢查為什么使用==而不是.equals()

Java null檢查為什么使用==而不是.equals()

繁星點點滴滴 2019-08-27 10:39:26
Java null檢查為什么使用==而不是.equals()在Java中,我被告知在進行空檢查時應該使用==而不是.equals()。這是什么原因?
查看完整描述

3 回答

?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

他們是兩個完全不同的東西。==比較變量包含的對象引用(如果有)。.equals()檢查兩個對象是否相等,根據他們的契約來確定平等意味著什么。根據合同,兩個不同的對象實例完全可能“相等”。然后有一個小細節(jié),因為equals是一個方法,如果你嘗試在引用上調用它null,你會得到一個NullPointerException。

例如:

class Foo {
    private int data;

    Foo(int d) {
        this.data = d;
    }

    @Override
    public boolean equals(Object other) {
        if (other == null || other.getClass() != this.getClass()) {
           return false;
        }
        return ((Foo)other).data == this.data;
    }

    /* In a real class, you'd override `hashCode` here as well */}Foo f1 = new Foo(5);Foo f2 = new Foo(5);System.out.println(f1 == f2);// outputs false, they're distinct object instancesSystem.out.println(f1.equals(f2));// outputs true, they're "equal" according to their definitionFoo f3 = null;System.out.println(f3 == null);// outputs true, `f3` doesn't have any object reference assigned to itSystem.out.println(f3.equals(null));// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anythingSystem.out.println(f1.equals(f3));// Outputs false, since `f1` is a valid instance but `f3` is null,// so one of the first checks inside the `Foo#equals` method will// disallow the equality because it sees that `other` == null


查看完整回答
反對 回復 2019-08-27
?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

如果你援引.equals()null你就會得到NullPointerException

因此,在調用適用的方法之前,始終建議檢查nullity

if(str!=null && str.equals("hi")){
 //str contains hi}



    查看完整回答
    反對 回復 2019-08-27
    ?
    達令說

    TA貢獻1821條經驗 獲得超6個贊

    從Java 1.7開始,如果你想比較兩個可能為null的對象,我推薦這個函數:

    Objects.equals(onePossibleNull, twoPossibleNull)

    java.util.Objects

    此類包含用于對對象進行操作的靜態(tài)實用程序方法。這些實用程序包括null-safe或null-tolerant方法,用于計算對象的哈希代碼,返回對象的字符串以及比較兩個對象。

    自:1.7


    查看完整回答
    反對 回復 2019-08-27
    • 3 回答
    • 0 關注
    • 1313 瀏覽
    慕課專欄
    更多

    添加回答

    舉報

    0/150
    提交
    取消
    微信客服

    購課補貼
    聯系客服咨詢優(yōu)惠詳情

    幫助反饋 APP下載

    慕課網APP
    您的移動學習伙伴

    公眾號

    掃描二維碼
    關注慕課網微信公眾號