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