Chance Smith
Chance Smith

Reputation: 33

ArrayList<String> to toString()

Im having trouble printing the ArrayList through to the toString. It says that I can not convert an ArrayList to an String. Here my code if anyone can help.

package edu.purse.test;

import java.util.ArrayList;

public class Purse 
  {
    ArrayList<String> coins = new ArrayList<String>();
    public Purse()
    {
    }
  public void addCoin(String coinName)
  {
    coins.add(coinName);
  }
  public String toString()
  {
      return  coins;
  }
}

package edu.purse.test;

public class PurseTester {
  public static void main(String[] args) {
    Purse p = new Purse();
    p.addCoin("Quarter");
    p.addCoin("Dime");
    System.out.println(p.toString());
  }
}

Upvotes: 0

Views: 446

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

You are returning an ArrayList when the method declares the return type as String. Use

public String toString()
{
    return coins.toString();
}

Note that explicitly calling toString() here

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

is unnecessary. There's an overloaded method that accepts an Object argument and internally calls toString(), a method that each class inherits from Object, a class which all classes implicitly extend in Java.

Upvotes: 4

Related Questions