簡體   English   中英

使用Java中的堆棧將對象添加到數組列表中

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

在此代碼中,由於不允許使用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);
       }

並不是全部要“隱藏” ArrayList嗎? 這就是為什么您添加了push()函數?

所以orderList.push(order); 應該是push(order);

 orderList.push(order);

orderList是ArrayList的引用,並且ArrayList類沒有push()方法。 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