简体   繁体   English

使用Java中的堆栈将对象添加到数组列表中

[英]adding an object into an array list using stack in java

In this code I tried to add a new order into the array list using stack since i'm not allowed to use add(), but when I try to call it the program shows an error saying that the push() method was not found, it be great if someone could tell me where I went wrong in the code 在此代码中,由于不允许使用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);
       }

Isn't the whole point to "hide" the ArrayList ? 并不是全部要“隐藏” ArrayList吗? That is why you added a push() function? 这就是为什么您添加了push()函数?

So orderList.push(order); 所以orderList.push(order); should be push(order); 应该是push(order); .

 orderList.push(order);

orderList is ref of ArrayList and ArrayList class does not have push() method. orderList是ArrayList的引用,并且ArrayList类没有push()方法。 https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html You should create an instance of your class "OrderArrayList" and call push() method on it. https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html您应该创建“ OrderArrayList”类的实例,并在其上调用push()方法。

OrderArrayList orderArrayList = new OrderArrayList();
...
...
//collect input from user
OrderList order = new OrderList(pcode, ccode, quantity);
orderArrayList.push(order);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM