黑马程序员---Object 中toString()与equal()方法

来源:互联网 发布:双色球红球最简单算法 编辑:程序博客网 时间:2024/05/01 05:25

------- android培训java培训、期待与您交流! ---------- 

 

黑马程序员---Object 中toString()与equal()方法

 

Object类是所有java类的根基类。Object中提供了许多方法,如toString(),equal()等,它们比许在重写之后才能使用,在某些类中提供了这些方法的重写但是很多情况下,需要程序员自己来重写这些方法进行使用。

在此以toString()进行说明。在在进行String与其他类型的数据的连接操作时,系统默认调用该对象的toString()方法,可以根据需要用户自定义类型中重写toString()方法,而在API文档说明中,也建议重写这个方法。

例如:在下面一段程序中

class Student {

Private String name;

Private int age

private int id;

Student(String name,int age,int id){

this.name = name;

this.age = age;

this.id = id ;

}

/*重写了toString()方法,再输出类Student的对象时,将按照重写方式进行输出*/

public String toString(){

return this.name+" "+this.age+" "+id ;

}

}

public class Test2{

public static void main(String args[]){

Student t1 = new Student("wanghaohua",24,1234) ;

System.out.println(t1);

}

}

当不重写toString()方法的很多情况下,想输出对象的哈希码;而不是t1的相应信息。

例如下面的一段程序中

class Dog{

}

public class Test{

public static void mian(String[] args){

Dog d = new Dog();

System.out.println("d:="+d.toString());

}

运行结果d:=Dog@64ea66

equals方法

Object的equal方法定义为:x equal(y)当x和y是同一个对象应用时返回true否则返回false

J2SDK提供的一些类,如String,Date等重写了这一方法,当此时运用equal时可以得到预想中的结果。

可以根据需要在用户自定义类型中重写equal方法。

用下面的代码说明

public class TestEqual {

public static void main(String[] args) {

Cat c1 = new Cat(1,2,3);

Cat c2 = new Cat(1,2,3);

System.out.println(c1.equals(c2));

}

}

class Cat {

  int color;

  int height,weight;

  Cat(int color,int height,int weight){

  this.color = color;

  this.height = height;

  this.weight = weight;

  }

  

  public boolean equals(Object obj) {   

  

  if(obj==nullreturn false;

  else{

  if(obj instanceof Cat){

  Cat c = (Cat)obj;

  if(c.color==this.color && c.height==this.height && c.weight==this.weight){

  return true;

  }

  }

  }

  return false;

  

  }

}

在以上的程序中,如果没有对equal进行重写的情况下,程序的输出将是错误的,即使对猫的赋值都相同,但是由于没有重写,对比的效果仍然和c1==c2的效果所以一样的。

 

 

------- android培训java培训、期待与您交流! ----------

0 0
原创粉丝点击