我这是我的代码,它将元素添加到 ArrayList
if(countries==null){
countries = new ArrayList();
for(int x = 0; x < data.getRowCount(); x++)
{
String shortName = data.getString(x,0);
String code = data.getString(x,1);
countries.add(x, new Country(code, shortName));
}
}
以下是迭代器代码
for( Iterator iter = countries.iterator(); iter.hasNext();)
{
Country country = (Country)iter.next();
Element optionselect = doc.createElement( "countryselect" );
optionselect.setAttribute( "name", country.getShortName() );//Getting NULL Pointer Exception
optionselect.setAttribute( "value", country.getCode() );
countriesElement.appendChild( optionselect );
}
现在我在行得到空指针异常:
optionselect.setAttribute( "name", country.getShortName() );
PS:我无法调试它,因为它正在生产中运行,我无法在本地服务器上复制它
乍一看,ArrayList 中似乎有一些 null 值,但从代码中我无法弄清楚它是如何可能的。
有人可以对此有所了解(也许是Java 5的错误)。
编辑:我也用这段代码得到空指针
List countryCodes = new ArrayList();
for (int x = 0; x < countries.size(); x++)
{
Country c = (Country) countries.get(x);
countryCodes.add(x, c.getCode());// Throwing Exception
}
这确认了一件事,即在某处null
对象countries List
,但查看代码我看不出这怎么可能
堆栈跟踪如下:
Stack Trace:java.lang.NullPointerException
at com.ilrn.controller.modules.Users.appendCountryList(Users.java:985)
at com.ilrn.controller.modules.Users.setupCountries(Users.java:1348)
at com.ilrn.controller.modules.Users.gen_add(Users.java:1329)
at com.ilrn.controller.modules.Users.generate(Users.java:190)
at com.ilrn.controller.ShellModule.generateShell(ShellModule.java:1958)
Users.java:985 是optionselect.setAttribute( "name", country.getShortName() );
Stack Trace(number 2):java.lang.NullPointerException
at com.ilrn.controller.dto.IlrnCountriesDTO.getCountryCodes(IlrnCountriesDTO.java:45)
at sun.reflect.GeneratedMethodAccessor471.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:592)
IlrnCountriesDTO.java:45 在哪里countryCodes.add(x, c.getCode());
另请注意,国家列表仅加载一次(第一次请求且国家/地区为私有时)
经过分析,我认为这是一个多线程问题。在查看 ArrayList 代码后,我发现它不是synchronized
(因此对于同一索引,大小可能增加了两次)
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
这是国家类(片段)
private String code_;
private String shortName_;
/**
* Constructor sets code and short name.
*
* @param code Specifies the code.
* @param shortName Specifies the short name.
*/
public Country(String code, String shortName)
{
code_ = code;
shortName_ = shortName;
}
public String getCode() {
return code_;
}
public String getShortName() {
return shortName_;
}