Jackson Minz
Jackson Minz

Reputation: 1

Passing array of objects in java and saving the array of objects in the called method

I wrote some code to return me an array of objects. How do I save those objects in the called method?

   public Ticket[] getOpenTicket() {
        int ticketcount = 0;
        for (int i = 0; i < ticket.length; i++) {
            if (ticket[i] != null && ticket[i].getResolvedBy() == null) {
                ticketcount = ticketcount + 1;
                // System.out.println("Ticket raised by : " +
                // ticket[i].getTicketno());
            }
        }

        Ticket[] opentickets = new Ticket[ticketcount];
        for (int i = 0; i < ticket.length; i++) {
            if (ticket[i].getResolvedBy() == null) {
                opentickets[i] = ticket[i];
            }
        }
        return opentickets;

    }

This is the called function from where I am calling openticket:

TicketDaoMemImpl tdmi=new TicketDaoMemImpl();
Ticket [] obj1=tdmi.getOpenTicket();

Thanks

Upvotes: 0

Views: 32

Answers (2)

nhouser9
nhouser9

Reputation: 6780

In this line of code

Ticket[] opentickets = new Ticket[ticketcount];
  for (int i = 0; i < ticket.length; i++) {
    if (ticket[i].getResolvedBy() == null) {

can't ticket[i] be null? It seems like that is most likely causing your issue - you call a method on what may be a null reference.

You should change you loop to something like:

Ticket[] opentickets = new Ticket[ticketcount];
int ticketIndex = 0;
for (int i = 0; i < ticket.length; i++) {
  if (ticket[i] != null && ticket[i].getResolvedBy() == null) {
    opentickets[ticketIndex] = ticket[i];
    ticketIndex++;
  }
}

Upvotes: 0

Kristian Ferkić
Kristian Ferkić

Reputation: 498

Shouldn't that look more like this:

public class CheckTicket {
    public Ticket [] openTicket() {
        return arrayOfTickets; // wherever that comes from
    }
}

CheckTicket cc = new CheckTicket();
Ticket[] t1 = cc.openTicket();

Upvotes: 1

Related Questions