LoginSignup
0
0

More than 1 year has passed since last update.

【Apex】オブジェクトを参照ではなく値で比較したい

Posted at

はじめに

テスト駆動開発の勉強中に、オブジェクトの等価性比較を行う場面がありました。

Apexで試してみると、、

System.debug(new Dollar(10) == new Dollar(10)); //false
System.debug(new Dollar(10) === new Dollar(10)); //false

どちらも参照で比較しているみたいですね。

値で比較したい時はどうするのでしょうか。

結論

ユーザ定義の型を値で比較したい時は、自前で比較メソッドを作る。

※ユーザ定義の型:プログラム上にクラス定義しているだけで、組織にオブジェクトが存在しないもの

例)

public with sharing class Dollar {
    public Integer amount;

    public Dollar(Integer amount){
        this.amount = amount;
    }
    
    //比較メソッド
    public Boolean equals(Dollar Dollar){
        return this.amount == Dollar.amount;
    }
}

=====の特徴

==

  • 標準オブジェクト・カスタムオブジェクト
    • 値比較になる
System.debug(new Account() == new Account()); //true
System.debug(new カスタムオブジェクト名__c() == new カスタムオブジェクト名__c()); //true
  • ユーザ定義のオブジェクト
    • 参照比較になる

===

どんな時も参照比較になる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0