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