user1964188
user1964188

Reputation: 9

Java array, prints something else

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) + "-");

    }
}   

}

Upvotes: 0

Views: 109

Answers (5)

Dwight DeGroff
Dwight DeGroff

Reputation: 610

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());
}

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198033

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.

Upvotes: 1

dty
dty

Reputation: 18998

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.

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168825

Have TestOrder override the toString() method.

Upvotes: 2

Hunter McMillen
Hunter McMillen

Reputation: 61512

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.

Upvotes: 7

Related Questions