简体   繁体   中英

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

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 ? That is why you added a push() function?

So orderList.push(order); should be push(order); .

 orderList.push(order);

orderList is ref of ArrayList and ArrayList class does not have push() method. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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