繁体   English   中英

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

[英]Passing array of objects in java and saving the array of 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;

    }

这是我在调用openticket时所调用的函数:

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

谢谢

那不应该看起来像这样:

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

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

在这行代码中

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

票证[i]不能为空吗? 似乎最有可能引起您的问题-您对可能为null引用的方法进行了调用。

您应该将循环更改为:

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