简体   繁体   English

在Java中传递对象数组并在调用的方法中保存对象数组

[英]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: 这是我在调用openticket时所调用的函数:

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

Thanks 谢谢

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();

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? 票证[i]不能为空吗? It seems like that is most likely causing your issue - you call a method on what may be a null reference. 似乎最有可能引起您的问题-您对可能为null引用的方法进行了调用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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