首页 > 解决方案 > 意外的 ArrayList 大小

问题描述

我有以下代码,

if(scores.size() <= 0) {
    scores.add(0, current);
    score1.setText(scores.get(0));
    Log.d(LOG_TAG, "array = " + scores.size());


} else if(scores.size() <= 1){
    scores.add(1, scores.get(0));
    scores.add(0, current);
    score1.setText(scores.get(0));
    score2.setText(scores.get(1));
    Log.d(LOG_TAG, "array = " + scores.size());
 } else if(scores.size() <= 2) {
    scores.add(2, scores.get(1));
    scores.add(1, scores.get(0));
    scores.add(0, current);
    score1.setText(scores.get(0));
    score2.setText(scores.get(1));
    score3.setText(scores.get(2));
    Log.d(LOG_TAG, "array = " + scores.size());
}

scores是一个ArrayList保持String值, currentString每次按下按钮并从EditText框中获取的值。

在运行代码时,我希望 中的元素数量ArrayList增加 1。但是 LogcatArrayList在第一次单击按钮后显示大小为 1,然后是 3,然后是 7。

我期望发生的是ArrayList每次增加 1,ArrayList index 0移动到index 1并将新值放在index 0

我不能指责我做错了什么。

标签: javaandroidarraylist

解决方案


You call multiple times an add method. Each call adds new element to an array and increase total size by one. If you call three times add, array size increase by three (3 * 1).

From the List documentation about void add(int index, E element):

Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

If you want to insert a new item at specified index and replace old without shift, use set method:

scores.set(0, current);

推荐阅读