Exception raised while adding an element into an ArrayList
I have an array list I am trying to add values into it and I am running into exception. I have used this code many times much still can't figure out what is creating this error, below is the code for your reference.
The line where I am using add method I get into a null pointer exception, All the above values are getting printed in console)
sid = new ArrayList<String>();
Enumeration e = Global.qtutlist.keys();
int qj=0;
//iterate开发者_如何转开发 through Hashtable keys Enumeration
while(e.hasMoreElements())
{
System.out.println("sid is key and its value id" );
System.out.println(Integer.parseInt(e.nextElement().toString()));
try
{
sid.add(e.nextElement().toString());
System.out.println("lenght is "+ sid.size());
}
catch(Exception ex)
{
System.out.println("caught exception is"+ex.getMessage());
}
}
you are calling nextElement()
twice in loop and checking once
make it as follows
while(e.hasMoreElements())
{ String item = e.nextElement().toString()
System.out.println("sid is key and its value id" );
System.out.println(Integer.parseInt(item));
try{
sid.add(item);
System.out.println("lenght is "+ sid.size());
}catch(Exception ex){
System.out.println("caught exception is"+ex.getMessage());
}
}
If it shows NumberFormatException
then one of the string isn't parsable to int
You're calling
e.nextElement()
Twice. Store it in a variable and operate on that variable instead
while(e.hasMoreElements()) {
Object o = e.nextElement();
// ...
}
You are using e.nextElement() twice. This can't work. Enumerations use the Iterator design pattern, which means that you may only access each element once, before the internal counter advances to the next object. Note that hasMoreElements() does not advance the cursor, only nextElement() does.
Store the result in a local variable and re-use that:
System.out.println("sid is key and its value id" );
String str = e.nextElement().toString();
System.out.println(Integer.parseInt(str));
try{
sid.add(str);
System.out.println("lenght is "+ sid.size());
}catch(Exception ex){
System.out.println("caught exception is"+ex.getMessage());
}
e.nextElement() is null that is the reason and you are doing an toString() operation on null
You invoke nextElement twice when you check item presence only once.
You are checking e.hasMoreElements()
once and call e.nextElement()
twice in the loop. Every call to nextElement()
increments the internal marker, so every time, the number of elements in your enumeration is odd, you get an NPE.
精彩评论