首页 > 代码库 > 代码模型:对象比较

代码模型:对象比较

 1 package cn.demo; 2 class Person{ 3     private String name; 4     private int age; 5     public Person(String name,int age){ 6         this.name = name; 7         this.age = age; 8     } 9     public boolean compare(Person per){10         if(per == null){11             return false;12         }13         if(this == per){14             return true;15         }16         if(this.name.equals(per.name) && this.age == age){17             return true;18         }19         return false;20     }21     public String getName() {22         return name;23     }24     public void setName(String name) {25         this.name = name;26     }27     public int getAge() {28         return age;29     }30     public void setAge(int age) {31         this.age = age;32     }33 }34 public class Test {35     public static void main(String[] args) throws Exception {36    Person per2 = new Person("李洋",23);37    Person per1 = new Person("李洋",23);38     if(per1.compare(per2)){39         System.out.println("是同一个对象。");40     }else{41         System.out.println("不是同一个对象 ");42     }43     }44 }

结果:是同一个对象。

代码模型:对象比较