使用.toString显示ArrayList

时间:2017-08-01 10:35:00

标签: java arraylist

在开始编写这个简单的程序后,我遇到了一个我很想解释的逻辑错误。 toString()方法当前正在打印geographylist.GeographyList@15db9742

测试类 -

public static void main(String[] args) {

    GeographyList g = new  GeographyList();


    g.addCountry ("Scotland");
    g.addCountry ("Wales");
    g.addCountry ("Ireland");
    g.addCountry ("Italy");

    System.out.println(g.toString());

ArrayList setup

public class GeographyList {

private ArrayList<String> countries;

public GeographyList(){
  countries = new ArrayList<>();
}

public ArrayList<String> getCountries() {
    return countries;
}

public String getCountry(int index){
    return countries.get(index);
}

public void addCountry(String aCountry){
  countries.add(aCountry);
  System.out.println(aCountry + " added.");
}

1 个答案:

答案 0 :(得分:2)

它打印geographylist.GeographyList@15db9742的原因是因为您没有打印ArrayList。您正在打印GeographyListGeographyList可能包含 ArrayList,但这是偶然的。

继承自the Object classtoString的默认实现是打印包名geographylist,类名GeographyList和哈希码15db9742

如果要覆盖此行为you will need to override the behaviour of toString,就像ArrayList类已经完成一样。

这可能看起来像这样:

public class GeographyList {
    //...

    @Override
    public String toString()
    {
        return countries.toString();
    }
}

或者,既然您已经能够从课堂上获得ArrayList,那么您可以致电

System.out.println(g.getCountries().toString());

而不是

System.out.println(g.toString());