java – ArrayList限制为保存10个值

栏目: Java · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/8969805/arraylist-limit-to-hold-10-values
我在我的代码中使用了一个ArrayList,它由EditText字段填充,但我想限制ArrayList,因此它只能容纳10个值.添加10个值后,如果另一个尝试添加,我只需要它不添加到数组中.任何人有任何想法如何做到这一点?
private static ArrayList<String> playerList = new ArrayList<String>();

在你的处理程序方法:

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

编辑:你的错误在这里:

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
}

您应该检查onClickListener内部的大小,而不是外部:

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

翻译自:https://stackoverflow.com/questions/8969805/arraylist-limit-to-hold-10-values


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Art of Computer Programming, Volume 3

The Art of Computer Programming, Volume 3

Donald E. Knuth / Addison-Wesley Professional / 1998-05-04 / USD 74.99

Finally, after a wait of more than thirty-five years, the first part of Volume 4 is at last ready for publication. Check out the boxed set that brings together Volumes 1 - 4A in one elegant case, and ......一起来看看 《The Art of Computer Programming, Volume 3》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具