Java 正确输出集合

1、第一种:

        List<String> strList=new ArrayList<String>();
        strList.add("hello");
        strList.add("test");
        System.out.println(strList);

输出结果:

[hello, test]

2、第二种:

package test;

public class Fruit {
    private String colour;
    private String name;

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

测试代码

        List<Fruit> test = new ArrayList<Fruit>();
        Fruit fruit = new Fruit();
        fruit.setColour("red");
        fruit.setName("apple");
        test.add(fruit);
        System.out.println(test);

输出:

[test.Fruit@15db9742]

重写toString方法

    @Override
    public String toString() {
        return "{name:" + name + ";colour:" + colour + "}";
    }

输出:

[{name:apple;colour:red}]

 

posted @ 2018-09-20 21:57  熊掌和鱼  阅读(2284)  评论(0)    收藏  举报