0

I have to create stack using an ArrayList, everything seems to be correct but for some reason the output to the console is: model.ArrayStack@a0dcd9 (the name of my package and the ArrayStack class).

Sophie
  • 13
  • 2

3 Answers3

1

You need to override toString in your ArrayStack class. Iterate over the elements and concatenate them into human readable format.

KobbyPemson
  • 2,519
  • 1
  • 18
  • 33
1

What you are getting is the output of the default toString() in Object class. If you want to print something meaningful then you need to Override the toString() method in your ArrayStack class.

public String toString()
{
   // iterate through your array and generate a String consisting of all elements

   // alternatively you can take advantage of the fact that Arraylist has already 
   // overriden toString() method to print all elements

  return st.toString();
}
Kakarot
  • 4,252
  • 2
  • 16
  • 18
  • Great! Now, would you happen to know why I can't put: st.size()? – Sophie Feb 27 '14 at 04:38
  • which line in the code are you referring to ? – Kakarot Feb 27 '14 at 04:39
  • In the Main class, within the try block: System.out.println(st); I also want to put System.out.println(st.size()); When I do, it tells me that "The method size() is undefined for the type ArrayStack." – Sophie Feb 27 '14 at 04:41
  • You cant use st.size() as there is no method size() in ArrayStack class. Define a method public int size() {return st.size();} inside ArrayStack class – Kakarot Feb 27 '14 at 04:43
  • Ah, I'm sorry, I'm fairly new to Java... – Sophie Feb 27 '14 at 04:47
  • @Sophie no worries..if this worked you can mark the answer as "Accepted Answer" – Kakarot Feb 27 '14 at 04:48
0

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

To print as I suspect you want it, you will need to iterate through the arrayList

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64