0

I'm trying to print the items from my array, but when I run the program, it prints out Orders:testorder@4, testorder@5 and so on. Any tips on how I can fix it so it writes 123 Buy?

package hej;


public class TestOrder {
public static void main(String[] args) {

    Order order1 = new Order("123", "Buy");
    Order order2 = new Order("456", "Sell");
    Order order3= new Order("231", "Buy");
    Order order4= new Order("987", "Buy");


    OrderRegister orderregister = new OrderRegister();


    orderregister.addOrder(order1);
    orderregister.addOrder(order2);
    orderregister.addOrder(order3);
    orderregister.addOrder(order4);


    System.out.println("Orders: ");        
    for (int i = 0; i < orderregister.getArrayList().size(); i++){
        System.out.println(orderregister.getArrayList().get(i) + "-");

    }
}   

}

1
  • 6
    Add a public String toString() method to Order which prints the way you want. Commented Jan 9, 2013 at 17:39

5 Answers 5

7

Because you don't have a toString() method defined for your Order class.

When Java tries to print an Object, it attempts to call the toString() method for that Object, if it can't find one it uses the toString() from the Object superclass.

And the Object toString() by default does this:

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

which is exactly what you are seeing as output.

Sign up to request clarification or add additional context in comments.

Comments

2

Have TestOrder override the toString() method.

Comments

1

When you concatenate an object with a String (like in your System.out.println(...) statements), the toString() method is called on the object to convert it to a String first.

You need to override the toString() method on your Order class and have it generate the string form of the order.

Comments

1

This is exactly what you should expect, given that you haven't told Java any other way to convert an Order to a String. Override Order.toString() if you want Java to use some particular way of converting an Order to a String.

Comments

1

You could/should try overriding the toString() method(which is called implicitly in your example) as others have suggested.

For example:

@Override public String toString()
{
return String.format("%s , %s", this.getID(), this.getAction());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.