0

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

4
  • Where is tickettype defined? Are you sure it has been initialized? Please post enough code that we can reproduce the issue. Commented Apr 2, 2016 at 17:32
  • yes i m sure it is initialised Commented Apr 2, 2016 at 17:58
  • See my answer now that you have updated your code. Commented Apr 2, 2016 at 18:32
  • Not sure if you've edited your question/post and removed something, but in the current code posted, you reference ticket which is presumably an array but it is never declared (unless you have it declared as a global array somewhere in your class?) As posted, this wouldn't compile. Commented Apr 2, 2016 at 18:42

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Tried the above code but it is still throwing a null pointer exceptions
0

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++;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.