Java集合之toString

当我们需要将结果转换为字符串输出的时候,调用toString方法,toString方法在输出的时候是默认调用的

package collection;

import java.util.ArrayList;

public class TestCollection {
    public static void main(String[] args) {
        ArrayList heros=new ArrayList();
        heros.add(new Hero("盖伦"));
        heros.add(new Hero("提莫"));      
        heros.add(1,new Hero("special hero"));
        System.out.println(heros.size());
        System.out.println(heros);
        System.out.println(heros.toString());

    }
}

输出结果为;
这里写图片描述
当重写了toString方法以后

package collection;

public class Hero {

    public String name;
    public float hp;
    public int damage;
    public Hero() {
        // TODO Auto-generated constructor stub
    }
    public Hero(String name){
        this.name=name;
    }
    public String getName() {
        return name;
    }

    public String toString(){
        return name;
    }
}

输出结果为:
这里写图片描述


版权声明:本文为OutThink原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。