Java – ArrayList Limit to hold 10 Values

androidjava

I am using an ArrayList within my code which gets populated by a EditText field but I am wanting to limit the ArrayList so it can only hold 10 values. After 10 values have been added if another tries to get added I just need it to not add into the Array. Anyone got any ideas how to do that?

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

Best Solution

In your handler method:

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

Edit: Your mistake is here:

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 the 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
            }
        }
     });