equals()方法

  比较内容    

    如a=new("1","2","3");

    b=new("1","2","3");

    如何比较a,b相同?a.equals(b)? (错误)

    需要对equals重写 

  如果希望不同内存但相同内容的两个对象equals时返回true,则需要重写equals

toString()方法

  输出当前对象地址
    如a=new();

    printf(a)与print(a.toString)相同 输出地址。

  想要得到返回值,就必须重写toString( )方法

例:

    在Person类中重写:

 1 public class Person {
 2     private String name;
 3     private int age;
 4     public Person() {
 5     }
 6     public Person(String name, int age) {
 7         this.name = name;
 8         this.age = age;
 9     }
10     public String getName() {
11         return name;
12     }
13     public void setName(String name) {
14         this.name = name;
15     }
16     public int getAge() {
17         return age;
18     }
19     public void setAge(int age) {
20         this.age = age;
21     }
22     //重写父类toString()
23     @Override
24     public String toString() {
25         return "Person [name=" + name + ", age=" + age + "]";
26     }
27     //重写父类equals方法
28     public boolean equals(Object obj) {
29         if (this == obj)
30             return true;
31         if (obj == null)
32             return false;
33         if (getClass() != obj.getClass())
34             return false;
35         Person other = (Person) obj;
36         if (age != other.age)
37             return false;
38         if (name == null) {
39             if (other.name != null)
40                 return false;
41         } else if (!name.equals(other.name))
42             return false;
43         return true;
44     }
45
46 }        

  在demo中调用执行

 1 public class Demo01 {
 2     public static void main(String[] args) {
 3         Person p=new Person("小红帽",18);
 4         Person p2=new Person("大灰狼",19);
 5         boolean flag=p.equals(p2);
 6         System.out.println(flag);
 7         System.out.println(p==p2);
 8         String s="aa";
 9         System.out.println(s.toString());
10         Person p=new Person("小红帽",18);
11         System.out.println(p);
12     }
13 }
14         

   结果显示:

  

01-20 01:24