2
class arrayList extends ArrayList<missedCall>
{
     public boolean add(missedCall m)
     {
        int i=size();
        if(i>10)
            remove(0);
        super.add(m);
        return true;
      }
 }

When I call the add method using user-defined class arrayList 11 times first element does not get removed.

Please provide the solution

Beri
  • 11,470
  • 4
  • 35
  • 57
gourav kumar
  • 141
  • 1
  • 11

2 Answers2

3

Your if(i>10) condition will only be true at the 12th call to this method, so calling the method 11 times will not remove the first element.

Perhaps you want to change your condition to :

if(i>=10)
    remove(0);
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Nitpicking: I would put { } around that. Not having the braces saves just a bit of typing; at the risk of running into annoying situations later when you forgot that you need them when adding another statement. – GhostCat Apr 14 '15 at 10:41
0

It makes for easier reading if you check the size after adding:

super.add(m);
if (size() > 10)
    remove(0);

Then you can keep your comparison, which makes sense: "if this size is too big, reduce it".

This is easier to understand than checking first, which would be like "if the size is going to be too big after the upcoming add, reduce it", which is less clear.

Bohemian
  • 412,405
  • 93
  • 575
  • 722