Java 谈谈toString( )方法

一、toString 方法介绍

toString方法是Java Object类的一个重要方法,通常用它来返回表示对象值的字符串。

toString方法是一种非常有用的调试工具,许多类中都有toString方法的定义,以便于用户获取有关对象状态的必要信息。


二、toString方法的重写

对于java工程师来说,重写(override) toString类是个很常见的操作。为了演示toString方法的重写,我们先来创建一个Hero对象,方便后面的演示。

package test;

public class Hero {
/*
 * define a class of heros
 * name
 * hp
 * damage
 * */
	private String name;s
	private int hp;
	private float damage;
	
	public Hero(String name) { //name
		this.name = name;
	}
	
	public void setHp(int hp) { //hp
		this.hp = hp;
	}
	
	public void setDamage(float damage) { //damage
		this.damage = damage;
	}
	
	public String getName() {
		return name;
	}
	
	public int getHp() {
		return hp;
	}
	
	public float getDamage() {
		return damage;
	}

	//public String toString() {
	//	return "Hero [" + getName() + ", " + getHp() + ", " + getDamage() + "]";
	//}
}

1、先来看看不重构toString方法的结果:

上面创建的Hero类,并没有重构toString方法。下面在一个test类用对象容器来保存创建的若干个Hero对象并输出,看看是什么效果。

package test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Random random = new Random();
		List<Hero> heroList = new ArrayList<Hero>();
		
		for(int i=0; i<5; i++) {
			Hero hero = new Hero("hero" + i);
			//hero.setName(name);
			hero.setHp(random.nextInt(500));
			hero.setDamage(random.nextFloat());
			heroList.add(hero);
		}
		System.out.println("初始化后的集合为:");
		System.out.println(heroList);
	}
}

输出为:

初始化后的集合为:
[test.Hero@3b192d32, test.Hero@16f65612, test.Hero@311d617d, test.Hero@7c53a9eb, test.Hero@ed17bee]

可以看到,此时打印出的是一串十六进制数。有人认为这是对象容器中,对象保存的地址,这个想法是错误的。其实,这里的值代表着对象容器中的对象的哈希值。不信的话,我们来看Java API文档中,对于toString( )的解释:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

2、再来看看在自定义类中加入重写toString方法后的结果:

对Hero类中,实现toString方法的重写,代码如下:

package test;

public class Hero {
/*
 * define a class of hero
 * name
 * hp
 * damage
 * */
	private String name;
	private int hp;
	private float damage;
	
	public Hero(String name) {
		this.name = name;
	}
	
	public void setHp(int hp) {
		this.hp = hp;
	}
	
	public void setDamage(float damage) {
		this.damage = damage;
	}
	
	public String getName() {
		return name;
	}
	
	public int getHp() {
		return hp;
	}
	
	public float getDamage() {
		return damage;
	}
	
    /*重写toString方法*/
	public String toString() {
		return "Hero [" + getName() + ", " + getHp() + ", " + getDamage() + "]";
	}
}

同样的,在test类进行测试:

package test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Random random = new Random();
		List<Hero> heroList = new ArrayList<Hero>();
		
		for(int i=0; i<5; i++) {
			Hero hero = new Hero("hero " + i);
			//hero.setName(name);
			hero.setHp(random.nextInt(500));
			hero.setDamage(random.nextFloat());
			heroList.add(hero);
		}
		System.out.println("初始化后的集合为:");
		System.out.println(heroList);
	}
}

我们来看看输出是什么:

初始化后的集合为:
[Hero [hero 0, 211, 0.9766653], Hero [hero 1, 1, 0.74892086], Hero [hero 2, 388, 0.8339275], Hero [hero 3, 364, 0.79060555], Hero [hero 4, 416, 0.38019073]]

总结:建议大家在自定义的类中都重写toString( )方法。


注意:

在初学期,我在类中重写toString方法时犯了这样一个错误:

public String toString() {
		return "Hero [" + Hero.getName() + ", " + Hero.getHp() + ", " + Hero.getDamage() + "]";
}

这时,IDE会报错:

Cannot make a static reference to the non-static method getName() from the type Hero

为什么呢?事实上,只有在调用静态方法的时候,可以直接用 类名.方法 的方式 (并且建议这么做)。而例子中的方法都不是静态方法(non-static),所以会报这样的错。

当然,这是个傻傻的错误,应该没有读者会犯这样的错叭

发布了26 篇原创文章 · 获赞 9 · 访问量 8219

猜你喜欢

转载自blog.csdn.net/weixin_41664064/article/details/104516309