Java 返回空的arraylist而不是null

Java 返回空的arraylist而不是null,java,Java,我需要调整此方法以返回一个空的“”,而不是null,因为我应该使用一个类来测试它,并且得到一个NullPointerException。如何将其更改为返回“”,而不是null /** * Return the specified number of mail items for a user or * null if there are none. * @param who The user requesting their next item. * @param howMany The

我需要调整此方法以返回一个空的“”,而不是
null
,因为我应该使用一个类来测试它,并且得到一个
NullPointerException
。如何将其更改为返回“”,而不是
null

/**
 * Return the specified number of mail items for a user or
 * null if there are none.
 * @param who The user requesting their next item.
 * @param howMany The number of mail items requested.
 * @return The user's specified number of next items.
 */
public ArrayList<MailItem> getNextMailItems(String who, int howMany)
{
    ArrayList<MailItem> itemsToReturn = new ArrayList<MailItem>();
    if(who != null)
    {
        who = formatName(who);
    }
    ArrayList<MailItem> mails = items.get((who));
    Iterator<MailItem> it = mails.iterator();
    while(it.hasNext() && howMany > 0)
    {
        MailItem item = it.next();
        it.remove();
        itemsToReturn.add(item);
        howMany--;
        return itemsToReturn;
    }
    return null;
}
/**
*为用户或用户返回指定数量的邮件
*如果没有,则为null。
*@param请求下一个项目的用户。
*@param请求的邮件数量。
*@返回用户指定数量的下一个项目。
*/
公共ArrayList getNextMailItems(字符串who,int howMany)
{
ArrayList itemsToReturn=新建ArrayList();
if(who!=null)
{
who=格式名称(who);
}
ArrayList mails=items.get((who));
Iterator it=mails.Iterator();
while(it.hasNext()&&howmount>0)
{
MailItem=it.next();
it.remove();
itemsToReturn.add(项目);
有多少——;
返回项目StoreTurn;
}
返回null;
}

我总是返回一个空列表,而不是空列表:

那么,我认为while循环中的返回是一个bug。在方法的开头,您创建的是一个空列表,所以为什么不在每种情况下都返回它呢

public ArrayList<MailItem> getNextMailItems(String who, int howMany)
{
    ArrayList<MailItem> itemsToReturn = new ArrayList<MailItem>();
    if(who != null)
    {
        who = formatName(who);
    }
    ArrayList<MailItem> mails = items.get((who));
    Iterator<MailItem> it = mails.iterator();
    while(it.hasNext() && howMany > 0)
    {
        MailItem item = it.next();
        it.remove();
        itemsToReturn.add(item);
        howMany--;
    }
    return itemsToReturn;
}
public ArrayList getNextMailItems(字符串who,int howmount)
{
ArrayList itemsToReturn=新建ArrayList();
if(who!=null)
{
who=格式名称(who);
}
ArrayList mails=items.get((who));
Iterator it=mails.Iterator();
while(it.hasNext()&&howmount>0)
{
MailItem=it.next();
it.remove();
itemsToReturn.add(项目);
有多少——;
}
返回项目StoreTurn;
}

如果
ArrayList mails=items.get((who))
返回null以下行返回null指针-
迭代器it=mails.Iterator()-因此,在获取迭代器之前,您应该检查null。

只需使用ArrayList构造函数:

return new ArrayList<MailItem>();
返回新的ArrayList();

返回新的ArrayList();为了避免NPE,你想要新的空列表吗?你确定这就是你的商业案例吗?@Nambari说了什么,我还有一个额外的问题。此方法是否会返回包含多个项目的
MailItem
s列表?