ArrayList constraint to save 10 values

I use ArrayListin my code that is populated with a field EditText, but I want to limit it ArrayList, so it can only contain 10 values. After adding 10 values, if another is trying to add, I just need to not add it to Array. Anyone have any ideas how to do this?

private static ArrayList<String> playerList = new ArrayList<String>();
+5
source share
4 answers

In the handler method:

if(playerList.size() < 10) {
   // playerList.add
} else {
   // do nothing
}

Change . Your mistake:

if(playerList.size() < 10) {

    Button confirm = (Button) findViewById(R.id.add);
    confirm.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    EditText playername = (EditText) findViewById(R.id.userinput);
    playerList.add(playername.getText().toString());
    adapter.notifyDataSetChanged();
    playername.setText("");

    }});
} else {
       // do nothing
}

You should check the size inside onClickListener, not outside:

    Button confirm = (Button) findViewById(R.id.add);
    confirm.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            EditText playername = (EditText) findViewById(R.id.userinput);
            if(playerList.size() < 10) {
               playerList.add(playername.getText().toString());
               adapter.notifyDataSetChanged();
               playername.setText("");
            } else {
                // do nothing
            }
        }
     });
+9
source

If you do not have control over a function that adds items to the list, you can override ArrayList add.

public class MySizeLimitedArrayList extends ArrayList<Object> {
  @Override
  public boolean add(Object e) {
      if (this.size() < 10) {
          return super.add(e);
      }
      return false;
  }
}
+8
source

ArrayList ; , :

public class FixedSizeLimitedArrayList extends ArrayList<Object> {
  @Override
  public boolean add(Object o) {

      int n=10;
      if (this.size() < n) {
          return super.add(o);
      }
      return false;
  }
}

:

+1
source

You change your installation method this way.

private static ArrayList<String> playerList = new ArrayList<String>();

public boolean addToPlayerList(String input) {
   if (playerList.size() < 10) {
      playerList.add(input);
      return true;   
   } else {
      return false;
   }
}

or

You can expand ArrayListand create your own custom class.

public class MyArrayList extends ArrayList {
  @Override
  public boolean add(String input) {
      if (this.size() < 10) {
          return super.add(input);
      } else {
          return false;
      }
  }
}
0
source

All Articles