簡體   English   中英

使用.toString顯示ArrayList

[英]Using .toString to display an 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設置

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 您正在打印GeographyList GeographyList可能包含 ArrayList ,但這是偶然的。

Object繼承的toString的默認實現是打印包名稱geographylist ,類名稱GeographyList和哈希碼15db9742

如果要覆蓋此行為, 則需要覆蓋toString的行為 ,就像ArrayList類自己完成一樣。

可能看起來像這樣:

public class GeographyList {
    //...

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

另外,由於您已經可以從類中獲取ArrayList ,因此可以調用

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

代替

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM