java - 意外的 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
值,
current
是String
每次按下按钮并从EditText
框中获取的值。
在运行代码时,我希望 中的元素数量ArrayList
增加 1。但是 LogcatArrayList
在第一次单击按钮后显示大小为 1,然后是 3,然后是 7。
我期望发生的是ArrayList
每次增加 1,ArrayList index 0
移动到index 1
并将新值放在index 0
我不能指责我做错了什么。
解决方案
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);
推荐阅读
- c++ - 对在类外声明的函数的未定义引用
- php - 带有 csrf 的 Laravel ajax 请求
- javascript - 我如何像冠状病毒一样设置 OpenStreetMap 的样式
- php - 致命错误:未捕获错误:调用未定义函数 redirect() PHP 注销会话
- amazon-web-services - 将 cloudformation 无服务器模板转换为 Terraform 的最佳方法
- typescript - 元素隐式具有“任何”类型,因为类型的表达式
- reactjs - 我应该同时使用 Facebook Relay 和 Redux
- python - Django中的购物车总价问题
- angular - Spring Boot 后端和 Angular 前端应用程序
- amazon-cloudformation - RDS OptionGroup 在通过 cloudformation for SQL Server 创建时不起作用