arraylist在java中使用堆栈将对象添加到数组列表中
在这段代码中,我尝试使用stack向数组列表中添加一个新的顺序,因为我不允许使用add(),但是当我尝试调用它时,程序显示一个错误,说找不到push()方法,如果有人能告诉我代码中哪里出错了,那就太好了
import java.util.ArrayList;
import java.util.Scanner;
public class OrderArrayList {
ArrayList<OrderList> orderList;
public OrderArrayList() {
orderList = new ArrayList();
}
public boolean isEmpty() {
return orderList.isEmpty();
}
public void push(OrderList x) {
orderList.add(x);
}
public void addOrder() {
Scanner input1 = new Scanner(System.in);
System.out.print("Product code: ");
String pcode = input1.nextLine();
Scanner input2 = new Scanner(System.in);
System.out.print("Customer Code: ");
String ccode = input2.nextLine();
Scanner input3 = new Scanner(System.in);
System.out.print("Quantity: ");
int quantity = input3.nextInt();
OrderList order = new OrderList(pcode, ccode, quantity);
orderList.push(order);
}
# 1 楼答案
“隐藏”这个
ArrayList
不是重点吗?这就是为什么添加了push()
函数所以
orderList.push(order);
应该是push(order);
# 2 楼答案
orderList是ArrayList的引用,ArrayList类没有push()方法。 https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html 您应该创建类“OrderArrayList”的实例,并对其调用push()方法