How to compare objects by multiple fields

后端 未结 22 2555
暖寄归人
暖寄归人 2020-11-22 00:43

Assume you have some objects which have several fields they can be compared by:

public class Person {

    private String firstName;
    private String lastN         


        
22条回答
  •  盖世英雄少女心
    2020-11-22 01:35

    It is easy to compare two objects with hashcode method in java`

    public class Sample{
    
      String a=null;
      String b=null;
    
      public Sample(){
          a="s";
          b="a";
      }
      public Sample(String a,String b){
          this.a=a;
          this.b=b;
      }
      public static void main(String args[]){
          Sample f=new Sample("b","12");
          Sample s=new Sample("b","12");
          //will return true
          System.out.println((s.a.hashCode()+s.b.hashCode())==(f.a.hashCode()+f.b.hashCode()));
    
          //will return false
          Sample f=new Sample("b","12");
          Sample s=new Sample("b","13");
          System.out.println((s.a.hashCode()+s.b.hashCode())==(f.a.hashCode()+f.b.hashCode()));
    
    }
    

提交回复
热议问题