我的ArrayList包含两条记录:
Item 1
Item 2
这是我用来获取这些记录的循环
String global = null;
for(int i=0; i<arrayList.size(); i++) {
String name = arrayList.get(i).getName().toString();
}
global = global+name+", ";
Log.d("items:", global);
输出:
D/items:: nullItem 2,
虽然我期待
Item 1, Item 2
最佳答案
将全局字符串初始化为空字符串而不是 null。不应在 null 和字符串对象之间进行串联。
String global ="";
global = global +"item"; // global is now item;
如果将 global 初始化为 null
String global = null;
global = global + "item"; // treated as "null" + "item"
在循环内修改全局变量,您试图在其范围之外访问 name 变量,因此即使您在循环外声明 name ,循环中的每次迭代也会覆盖 name 变量。
for(int i=0; i<arrayList.size(); i++) {
String name = arrayList.get(i).getName().toString();
global = global+name+", ";
}
关于java - For循环从ArrayList中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36352407/