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
ArrayList
doesn't have a way of limiting the size; you could extend it to include a limit:
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;
}
}
Other options include:
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
}
}
});
If you don't have control over the function that adds elements to the list, you might want to override the ArrayList
add
.
public class MySizeLimitedArrayList extends ArrayList<Object> {
@Override
public boolean add(Object e) {
if (this.size() < 10) {
return super.add(e);
}
return false;
}
}
You modify you setter method like this.
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 extend ArrayList
and create your own customized class.
public class MyArrayList extends ArrayList {
@Override
public boolean add(String input) {
if (this.size() < 10) {
return super.add(input);
} else {
return false;
}
}
}