Sunday, 29 September 2013

How do I print an Object of MyList?

How do I print an Object of MyList?

Any time I try to print a MyList object I get 'User@' some hex number. Can
someone help me out with a printing function or a way to print in the
main? I heard of trying to Override the toString function, but I couldn't
seem to get that to work and am not sure if thats the correct thing to do.
public class MyList {
private ListElement head, tail; //Forward declaration
void add(Object value) {
if (tail != null) {
tail.next = new ListElement(value);
tail = tail.next;
}
else {
head = tail = new ListElement(value);
}
}
Object remove()
{
assert head != null; // don't remove on empty list
Object result = head.value;
head = head.next;
if (head == null) { //was that the last?
tail = null;
}
return result;
}
//Nested class needed only in the implementation of MyList
private class ListElement {
ListElement(Object value) {this.value = value;}
Object value;
ListElement next; //defaults to null as desired
}
public static void main(String[] args) {
myList anInstance = new myList();
String someValue = "A list element";
anInstance.add(someValue);
String anotherValue = "Another value";
anInstance.add(anotherValue);
}
}

No comments:

Post a Comment