gpt4 book ai didi

java - 使用 .toString 显示 ArrayList

转载 作者:行者123 更新时间:2023-12-01 20:17:59 24 4
gpt4 key购买 nike

开始编写这个简单的程序后,我遇到了一个逻辑错误,我希望对此进行解释。 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设置

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.");
}

最佳答案

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

toString 的默认实现,继承自 the Object class ,就是打印包名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());

关于java - 使用 .toString 显示 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45435489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com