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}]

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM