Java 使用.toString显示ArrayList

Java 使用.toString显示ArrayList,java,arraylist,Java,Arraylist,在开始编写这个简单的程序后,我遇到了一个逻辑错误,我想解释一下。toString()方法当前正在打印geographylist。GeographyList@15db9742 测试班- public static void main(String[] args) { GeographyList g = new GeographyList(); g.addCountry ("Scotland"); g.addCountry ("Wales"); g.addCo

在开始编写这个简单的程序后,我遇到了一个逻辑错误,我想解释一下。
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());
阵列列表设置

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.");
}
公共类地理目录{
私营ArrayList国家;
公共地理学家(){
国家/地区=新阵列列表();
}
公共阵列列表getCountries(){
返回国;
}
公共字符串getCountry(int索引){
返回国家。获取(索引);
}
公共国家/地区(字符串A国家/地区){
国家。添加(a国家);
System.out.println(accountry+“添加”);
}

它打印地理图表列表的原因。GeographyList@15db9742是因为您没有打印
ArrayList
。您正在打印
GeographyList
GeographyList
可能包含
ArrayList
,但这是偶然的

继承自的
toString
的默认实现是打印包名
geographylist
、类名
geographylist
和哈希代码
15db9742

如果您想覆盖此行为,就像
ArrayList
类本身所做的那样

可能看起来像这样:

public class GeographyList {
    //...

    @Override
    public String toString()
    {
        return countries.toString();
    }
}
或者,由于您已经能够从类中获取
ArrayList
,因此可以调用

System.out.println(g.getCountries().toString());
而不是

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

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

继承自的
toString
的默认实现是打印包名
geographylist
、类名
geographylist
和哈希代码
15db9742

如果您想覆盖此行为,就像
ArrayList
类本身所做的那样

可能看起来像这样:

public class GeographyList {
    //...

    @Override
    public String toString()
    {
        return countries.toString();
    }
}
或者,由于您已经能够从类中获取
ArrayList
,因此可以调用

System.out.println(g.getCountries().toString());
而不是

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

在类中实现
toString()
以获得所需的输出。
g.toString()
将打印
g
object的引用谢谢,您花了很多时间来研究这一点,因为有这样一个明显的错误:)。在类中实现
toString()
以获得所需的输出的可能重复的可能重复的实现。
g.toString>()
将打印
g
object的参考谢谢你,花了好长时间才看到这样一个明显的错误:)。可能的重复