将元素添加到列表

时间:2017-12-10 15:26:01

标签: salesforce apex-code apex force.com

在向列表中添加元素时,我收到了一个螺母指针异常。 错误是System.NullPointerException:尝试取消引用out.add(Time.newInstance(17,00,00,00));上的空对象

public class BusScheduleCache 
{   //Variable
private Cache.OrgPartition part;

//Constructor 
public BusScheduleCache()
{
    Cache.OrgPartition newobj = Cache.Org.getPartition('local.BusSchedule');
    part = newobj;
}

//methods
public void putSchedule(String busLine, Time[] schedule)
{
    part.put(busline, schedule);
}

public Time[] getSchedule (String busline)
{
    Time[] out = new List<Time>();

    out = (Time[]) part.get(busline);
    if (out == null)
    {
        out.add(Time.newInstance(8, 00, 00, 00));
        out.add(Time.newInstance(17,00,00,00));

    }

        return out;

}

}

1 个答案:

答案 0 :(得分:1)

问题是您正在检查列表out是否为null

if (out == null) { }

在这种情况下,您将添加到null列表。

同时回顾以下两行:

Time[] out = new List<Time>();

out = (Time[]) part.get(busline);

首先使用新列表实例化变量out,然后再次为其指定null引用。

做这样的事情可能很有用:

Time[] out = part.containsKey(busline) ? 
                     (Time[]) part.get(busline) : new List<Time>();
if (out.isEmpty())
{
    out.add(Time.newInstance(8, 00, 00, 00));
    out.add(Time.newInstance(17,00,00,00));
}

return out;