0
我有一个保存ArrayList的类。 我想通过调用testClass中的getOrderItems方法来打印该数组中的所有项目。我遇到了麻烦,数组元素返回的方式。从Java中的ArrayList打印元素
这里是类:
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:
------
[[email protected], [email protected], [email protected]]
null
或者覆盖[Object#toString](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString())或访问您想要打印的字段一个方法。 – SomeJavaGuy