[英]why does the list size return 0?
why the list size return 0 in toast? 为什么列表大小在吐司中返回0?
Activity Class 活动课
List<Models> models= new ArrayList<>();
List<String> Images = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
putData();
Toast.makeText(this, "" + models.get(0).Images.size(), Toast.LENGTH_SHORT).show();
}
void putData() {
for (int x = 1; x <= 6; x++) {
Images.add(String.valueOf(x) + ".png");
}
models.add(new Model(Images));
Images.clear();
}
Model Class 型号类别
public class Models {
List<String> Images;
public Models(List<String> images) {
Images = images;
}
}
I hope you help me........................................................... 我希望你能帮助我.................................... ..............
Because of this line: 由于这一行:
Images.clear();
which clears the list Images
. 这将清除Images
列表。
Maybe you think that Images
and models.get(0).Images
are 2 different lists. 也许您认为Images
和models.get(0).Images
是2个不同的列表。
They are not as they both point to the same list. 它们不是相同的,因为它们都指向同一列表。
Remove this 删除这个
List<String> Images = new ArrayList<>();
from your activity class declarations and change putData()
: 从您的活动类声明并更改putData()
:
void putData() {
List<String> Images = new ArrayList<>();
for (int x = 1; x <= 6; x++) {
Images.add(String.valueOf(x) + ".png");
}
models.add(new Model(Images));
}
You've called clear() on the images. 您已经在图像上调用了clear()。 They are gone by the point you call size(). 您调用size()时它们就消失了。
Because you're retaining the instance of Images
and then calling clear()
on it. 因为您要保留Images
实例,然后在其上调用clear()
。
When you create a new ArrayList in Java, something like: 用Java创建新的ArrayList时,类似:
ArrayList<Something> somethings = new ArrayList<>();
and then pass it to another class: 然后将其传递给另一个类:
SomeClass someClass = new SomeClass(somethings);
the ArrayList contained by SomeClass is the exact same one referenced by somethings
. SomeClass包含的ArrayList 与 somethings
引用的数组完全相同 。
When you call putData()
, you're passing a single instance of your ArrayList to your Models class. 调用putData()
,您putData()
ArrayList的单个实例传递给Models类。
You do fill it, but then you immediately clear it. 您确实填充了它,但是随后您立即清除了它。 Since you clear the Images
list in your putData()
class, you also clear the Images
list in your Models instance, because the two lists are the same. 由于您清除了putData()
类中的Images
列表,因此您putData()
Models实例中的Images
列表,因为这两个列表相同。
Make it a local variable and remove the clear()
: 将其设置为局部变量并删除clear()
:
void putData() {
ArrayList<String> Images = new ArrayList<>();
for (int x = 1; x <= 6; x++) {
Images.add(String.valueOf(x) + ".png");
}
models.add(new Model(Images));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.