0

I have a class which holds an ArrayList. I'd like to be able to print all items from that array, by calling a getOrderItems method in a testClass. I am having trouble, with the way the array elements are returned.

Here is the class:

package shopping;

import java.util.ArrayList;

public class ShoppingCart {
    private ArrayList<Item> list;


    public ShoppingCart() {
        this.list = new ArrayList<Item>(5);
    }

    public void addItem(Item item1) {
        this.list.add(item1);
    }

    public int getTotal() {
        int total = 0;

        for(Item it : list) {
            total = total + it.getCost();
        }
        return total;
    }

    public void removeItem(Item item1) {
        this.list.remove(item1);
    }

    public int finalizeOrder() {
        int cartSize = this.list.size();
        return cartSize;
    }

    //print elements from ArrayList<Item>
    public String getOrderItems() {
        System.out.println(this.list);
    return null;
  }

}

Here is the block from testClass:

//email possible & create
        int emailPossible = card.verifyCard();
        if (emailPossible > 0) {
            System.out.println("Email object has been added");
            System.out.println("Your orders was successful and has been placed.\nHere are the details of your order: \n");
            System.out.println("Items:\n------");
            System.out.println(cart.getOrderItems());
        }else{
            System.out.println("Email object has not been added");
        }
        //end email possible & create

However, my output appears to be printing the address of each item and not the item themselves:

Email object has been added
Your orders was successful and has been placed.
Here are the details of your order: 

Items:
------
[shopping.Item@677327b6, shopping.Item@14ae5a5, shopping.Item@7f31245a]
null
1
  • either override Object#toString or acces the field you want to print with a method. Commented Sep 28, 2016 at 10:49

2 Answers 2

0

You should override the toString() method for the Item class. It will allow you to print its objects in the custom way.

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

Comments

0

Implement toString by overriding object's superclass method in your class and you'll be able to print the list as string and not as reference.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.