Compare two objects with .equals() and == operator

前端 未结 15 1555
礼貌的吻别
礼貌的吻别 2020-11-22 01:13

I constructed a class with one String field. Then I created two objects and I have to compare them using == operator and .equals() too

15条回答
  •  醉梦人生
    2020-11-22 01:51

    The best way to compare 2 objects is by converting them into json strings and compare the strings, its the easiest solution when dealing with complicated nested objects, fields and/or objects that contain arrays.

    sample:

    import com.google.gson.Gson;
    
    
    Object a = // ...;
    Object b = //...;
    String objectString1 = new Gson().toJson(a);
    String objectString2 = new Gson().toJson(b); 
    
    if(objectString1.equals(objectString2)){
        //do this
    }
    

提交回复
热议问题