Hi I'm trying to write a toString() method for a generic LinkedStack but I'm having trouble
My class has two push methods. One pushes elements of some type onto the stack. It takes in some generic element and pushes it onto the stack. The other method takes in some generic stack and pops all of its elements onto the current stack.

So I have something like

public LinkedStack<T> copyStack(){
 //code goes here
}

To test my code I created a LinkedStack<String> object and pushed items onto it.
I then used some of the LinkedStack methods to modify and printed the final results
But instead of getting the items on the stack, I got pointers to memory address
I'm not sure how I would implement a toString() method to handle this.
Any help is appreciated.
Thanks

Recommended Answers

All 4 Replies

ig you hry those 'pointers', that means you are calling the toString method on an instance of a class which didn't override the toString method, but rather uses the one provided by the Object class.

not sure whether you'll have a foolproof solution for this, since you are using a 'default generic', which would allow any class, so you won't be able to verify yourself whether or not they implemented their own version of toString.

Sounds like you may be printing your stack elements (ie your class with a data item and the pointer to the next elements)? If so you need to provide a toString method for that class, in which you could return something like "List element: " + theDataItem. The string concatemation will automatically call the data item's toString method for you.

I'm lost.

Figured, rather found the soln

String="";
Node<E> current=top;//Node current=top for non generic stack
while(current!=null){
    result=result+(current.getData()).toString+"\n";
    current=current.getLink();
}
return result;}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.