向列表添加元素时出现空指针异常
null pointer exception in adding element to list
我在向列表中添加元素时遇到 nut 指针异常。
错误是 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;
}
}
问题是您正在检查列表 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;
我在向列表中添加元素时遇到 nut 指针异常。
错误是 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;
}
}
问题是您正在检查列表 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;