2017-08-01 30 views
0

開始編寫這個簡單的程序後,我遇到了一個我很想解釋的邏輯錯誤。該toString()方法正在打印[email protected]使用.toString顯示ArrayList

測試講座

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

在你的類中實現'toString()'來獲得你想要的輸出。 –

+0

'g.toString()'將打印'g'對象的引用 – Ali

+1

謝謝,花了很多年看這個明顯的錯誤:)。 – eGathergood

回答

2

它打印[email protected]的原因是因爲你不打印的ArrayList。您正在打印GeographyList。 A GeographyList可能包含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());