返回首页
当前位置: 主页 > 网络编程 > Jsp实例教程 >

关于java中toString方法详解

时间:2011-05-24 10:27来源:知行网www.zhixing123.cn 编辑:麦田守望者

toString方法用于表示对象值的字符串.
绝大多数的toString方法遵循这样的格式:类的名字,随后是一对方括号括起来的域值.下面是Employee类中的toString方法的实现(后面附上完整程序):

public String toString()
{
return"Employee[name"+name+",salary="+salary+",hireDay="+hireDay+"]";
}
实际上,还可以设计的更好一些,最好通过调用getClass().getName()得到类名得字符串,而不要将类名硬加到toString方法中.

public String toString()
{
return getClass().getName()+"[name+"+name+",salary="+salary+
",hireDay="+hireDay+"]";
}
toString方法也可以供子类调用.当然在设计子类时也应该定义自己得toString方法,并将子类得描述添加进去.如果超类使用了getClass().getName(),那么子类仅调用super.toString()就可以了,例如,下面是Manager类中的toString方法:
Class Manager extends Employee
{
.......
public String toString()
{
return super.toString()
+"[bonus="+bonus+"]";
}
}
调用toString:只要对象与一个字符串通过操作符"+"连接起来,java编译就会自动地调用toString方法,以便获得这个对象字符串描述.例如:
Point p=new Point(10,20);
String message="The current position is"+p;
//automatically invokes p.toString()
强烈建议为自己编写的每一个类增加toString方法.这样不仅自己受益,而且所有使用这个类的程序员也都会受益菲浅.
 

下面这个程序实现了Employee和Manager类的toString,equals和hashCode方法.

import java.util.*;

public class EqualsTest
{
public static void main(String[] args)
{
Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
Employee alice2 = alice1;
Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);

System.out.println("alice1 == alice2: " + (alice1 == alice2));

System.out.println("alice1 == alice3: " + (alice1 == alice3));

System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));

System.out.println("alice1.equals(bob): " + alice1.equals(bob));

System.out.println("bob.toString(): " + bob);

Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
System.out.println("boss.toString(): " + boss);
System.out.println("carl.equals(boss): " + carl.equals(boss));
System.out.println("alice1.hashCode(): " + alice1.hashCode());
System.out.println("alice3.hashCode(): " + alice3.hashCode());
System.out.println("bob.hashCode(): " + bob.hashCode());
System.out.println("carl.hashCode(): " + carl.hashCode());
}
}

class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}

public String getName()
{
return name;
}

public double getSalary()
{
return salary;
}

public Date getHireDay()
{
return hireDay;
}

public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}

public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical

if (this == otherObject) return true;

// must return false if the explicit parameter is null

if (otherObject == null) return false;

// if the classes don't match, they can't be equal

if (getClass() != otherObject.getClass())
return false;

// now we know otherObject is a non-null Employee

Employee other = (Employee) otherObject;

// test whether the fields have identical values

return name.equals(other.name)
&& salary == other.salary
&& hireDay.equals(other.hireDay);
}

public int hashCode()
{
return 7 * name.hashCode()
+ 11 * new Double(salary).hashCode()
+ 13 * hireDay.hashCode();
}

public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}

private String name;
private double salary;
private Date hireDay;
}

class Manager extends Employee
{
public Manager(String n, double s, int year, int month, int day)
{
super(n, s, year, month, day);
bonus = 0;
}

public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}

public void setBonus(double b)
{
bonus = b;
}

public boolean equals(Object otherObject)
{
if (!super.equals(otherObject)) return false;
Manager other = (Manager) otherObject;
// super.equals checked that this and other belong to the same class

return bonus == other.bonus;
}

public int hashCode()
{
return super.hashCode()
+ 17 * new Double(bonus).hashCode();
}

public String toString()
{
return super.toString()
+ "[bonus=" + bonus
+ "]";
}

private double bonus;
}

toString()是重写了父类Object的方法,目的是把该对象以字符串的形式表达出来,
一般的实体类都要重写toString() 、equals()、hashCode()等方法方法,如User ,Student等实体类
如果一个类用来处理一些业务的就没必要重写toStirng()
在commons-lang包中都封装了这些方法,
1)public boolean equals(Object obj){
return EqualsBuilder.reflectionEquals(this.obj);
}
2)public int hashCode(){
return HashCodeBuilder.reflectionHashCode(this);
}
3)public String toStirng(){
teturn ToStringBuilder.reflectionToString(this);
}

java中的toString()函数用法
在java中,所有对象都有toString()这个方法,因为它是Object里面已经有了的方法,而所有类都是继承Object,所以“所有对象都有这个方法”
它通常只是为了方便输出,比如System.out.println(xx),括号里面的“xx”如果不是String类型的话,就自动调用xx的toString()方法
toString就是让你重写用以在调用的时候输出你像要输出的信息的,谁调用它就把谁换成字符串形式 ,toString()方法返回对象的字符串表示;
也就是当打印输出一个对象时,系统自动调用其toString方法,打印的是toString方法的返回值。
总而言之,它只是sun公司开发java的时候为了方便所有类的字符串操作而特意加入的一个方法
例子1:
public class A{
public String toString(){return "this is A";}
}
如果某个方法里面有如下句子:
A obj=new A();
System.out.println(obj);
会得到输出:this is A
例子2:
public class A{
public String getString(){return "this is A";}//toString改个名字试试看
}
A obj=new A();
System.out.println(obj); //隐式调用toString()函数
//因为没用自定义toString()函数的返回值,所以会得到输出:xxxx@xxxxxxx的类名加地址形式 ;
System.out.println(obj.getString()); //显式调用getString()函数,会得到输出:this is A

  所以,toString的好处是在碰到“println”之类的输出方法时会自动调用,不用显式打出来

------分隔线----------------------------
标签(Tag):Java JAVA实例教程 JAVA基础教程 Java源代码
------分隔线----------------------------
推荐内容
猜你感兴趣