Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList Limit to hold 10 Values

Tags:

java

android

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>();
like image 592
Matt Avatar asked Jan 23 '12 09:01

Matt


People also ask

How many values can an ArrayList hold?

Since ArrayList in Java is backed by a built-in array, the limit on the size is equal the same as the limit on the size of an array, i.e. 2147483647.

How do you limit an ArrayList to 10 and show next 10 items on click of more?

you can handle it by yourself in getCount() method. you can put a integer in your adapter class and by each click on more button increase it 1.

How many values can a list hold?

A list can hold 1000 elements(as per the limit).

How do you restrict the size of an ArrayList in Java?

trimToSize() method is used for memory optimization. It trims the capacity of ArrayList to the current list size. For e.g. An arraylist is having capacity of 15 but there are only 5 elements in it, calling trimToSize() method on this ArrayList would change the capacity from 15 to 5.


2 Answers

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
            }
        }
     });
like image 56
Tudor Avatar answered Oct 19 '22 16:10

Tudor


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;
  }
}
like image 42
Sapan Diwakar Avatar answered Oct 19 '22 16:10

Sapan Diwakar