Reputation: 16040
I need to remove ith element from the list.
List<MyElement> MyList = new ArrayList<MyElement>();
for (int i=0; i<5; i++)
{
MyElement em = new MyElement(i);
MyList.add(em);
}
MyList.remove(3);
As a result MyList looks like this:
[0][1][2][4][null]
instead of this:
[0][1][2][4]
How to remove null
element?
Upvotes: 1
Views: 826
Reputation: 44813
try this, it does not assume that the null is at the end.
Iterator<MyElement> ml = MyList.iterator();
while (ml.hasNext()) {
MyElement em = ml.next(); // must be called before you can call ml.remove()
if (em == null) {
ml.remove();
}
}
Upvotes: 2