0

After starting to write a this simple program I have encountered a logic error that I would love explained. The toString() method is currently printing geographylist.GeographyList@15db9742

Test Class-

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.");
}
eGathergood
  • 31
  • 1
  • 8
  • Implement `toString()` in your class for your desired output. – Murat Karagöz Aug 01 '17 at 10:35
  • `g.toString()` will print the reference of `g` object – Ali Faris Aug 01 '17 at 10:38
  • 1
    Thank you, spent ages looking at this for such an obvious mistake :) . – eGathergood Aug 01 '17 at 10:39
  • Possible duplicate of [How to print out all the elements of a List in Java?](https://stackoverflow.com/questions/10168066/how-to-print-out-all-the-elements-of-a-list-in-java) – Murat Karagöz Aug 01 '17 at 10:41
  • Possible duplicate of [How do I print my Java object without getting "SomeType@2f92e0f4"?](https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4) – Tom Aug 01 '17 at 10:41

1 Answers1

3

The reason it prints geographylist.GeographyList@15db9742 is because you are not printing an ArrayList. You are printing a GeographyList. A GeographyList may contain an ArrayList, but that's incidental.

The default implementation of toString, inherited from the Object class, is to print the package name geographylist, the class name GeographyList and the hash code 15db9742.

If you want to override this behaviour, you will need to override the behaviour of toString, just as the ArrayList class will have done itself.

That might look something like this:

public class GeographyList {
    //...

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

Alternatively, since you already have the ability to get the ArrayList from your class, you could call

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

instead of

System.out.println(g.toString());
Michael
  • 41,989
  • 11
  • 82
  • 128