我有一个包含ArrayList的类。 我希望能够通过在testClass中调用getOrderItems方法来打印该数组中的所有项目。我遇到了麻烦,返回了数组元素的方式。
这是班级:
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;
}
}
这是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
但是,我的输出似乎是打印每个项目的地址而不是项目本身:
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
答案 0 :(得分:0)
您应该覆盖toString()
类的Item
方法。它允许您以自定义方式打印其对象。
答案 1 :(得分:0)
通过覆盖类中对象的超类方法来实现toString,并且您能够将列表打印为字符串而不是参考。