Add Elements from one class to an arraylist in another class

Asked

Viewed 58 times

0

I have a class Ticket, that creates a ticket. and I have to do a class CustomerService with a ArrayList Ticket type, which I called tickets and places all tickets created in this Arraylist.

Constructor of the Ticket class:

   public Ticket(char attendanceType, int ticketNumber)
    {
     this.arriveTime = LocalDateTime.now();
     this.attendanceTime = null;
     this.attendanceType = validateAttendanceType(attendanceType);
     this.waitTime = 0;
     this.ticketNumber = validateTicketNumber(ticketNumber);
    }
  • Your question is how to instantiate the ArrayList ? Or how to put the elements inside ? Has the method add of ArrayList to add elements.

  • He wants to know how to get the Arraylist of the other class, as far as I know.

  • Put the elements in this Ticket case, in the arraylist in the Customerservice class,

  • ex: person creates 1,2,3,4... tickets, ticket1,ticket2.. , and the program that starts the Customerservice class, puts all these tickets in the arrayList tickets

  • I think my answer will help you, @Miguel.

2 answers

0

From what I understand, your question is very simple, just create a method in the class Customerservice:

public class CustomerService {

private ArrayList<Tickets> tickets;

public CustomerService(){
    this.tickets = new ArrayList<>();
}

public void addTicket(Tickets t){
    tickets.add(t);
}
}

0

If you need an instance of CustomerService throughout the execution of your application, I recommend following a Singleton standard:

public class CustomerService {

    private static CustomerService INSTANCIA;

    private ArraList<Ticket> tickets;

    public static CustomerService getInstancia() {
        if (INSTANCIA == null) {
            INSTANCIA = new CustomerService();
            INSTANCIA.setTickets(new ArrayList<>());
        }

        return INSTANCIA;
    }

    public ArrayList<Ticket> getTickets() {
        return tickets;
    }

    public void setTickets(ArrayList<Ticket> tickets) {
        this.tickets = tickets;        
    }
    ...
}

From there, you need to run CustomerService.getInstancia().getTickets() to get the list of tickets and insert the object you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.