Klausos Klausos
Klausos Klausos

Reputation: 16040

Remove ith element from the ArrayList

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

Answers (2)

Scary Wombat
Scary Wombat

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

Autocrab
Autocrab

Reputation: 3747

call MyList.trimToSize() after removing element.

Upvotes: 2

Related Questions