[英]How to create lists dynamically using for loop in Java
Here's what I am doing: 1. fetch array from server 2. using Asynctask, I am catching the string in my onPostExecute method 3. iterating through array list and creating the list according to the string values of the array.这是我正在做的事情: 1. 从服务器获取数组 2. 使用 Asynctask,我在我的 onPostExecute 方法中捕获字符串 3. 遍历数组列表并根据数组的字符串值创建列表。
But I am getting this error "Variable 'result' is already defined in this scope", i tried searching over the net.但我收到此错误“变量‘结果’已在此范围内定义”,我尝试通过网络搜索。 But in vain.
但徒劳无功。 I don't understand the problem.
我不明白这个问题。
Here's the code:这是代码:
@Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
HashMap<String, List<String>> MoviesDetails = new HashMap<String, List<String>>();
int count = result.length;
for(int i=0; i<count;i++){
List<String> result[i] = new ArrayList<String>();
}
}
Thanks In advance提前致谢
You have String[] result already defined.您已经定义了 String[] 结果。 Change
改变
List<String> result[i] = new ArrayList<String>();
to some another variable到另一个变量
The reason you are getting the error is this:您收到错误的原因是:
You have String[] result
in your arguments.您的参数中有
String[] result
。 Then you try to define a List<String> result
.然后你尝试定义一个
List<String> result
。 So the compiler complains that you have two variables with same name.所以编译器抱怨说你有两个同名的变量。
Two things wrong here:这里有两点错误:
There is already a result variable on the onPostExecute() function. onPostExecute() 函数中已经有一个结果变量。 Try renaming your other result variable.
尝试重命名您的其他结果变量。
You cannot use the [] operator on what you are trying to achieve.您不能对您要实现的目标使用 [] 运算符。
What exactly are you trying to store: A list of strings, or a list of (ArrayList)?您究竟要存储什么:字符串列表或 (ArrayList) 列表?
Try like this:试试这样:
@Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
int count = result.length;
List<String> list = new ArrayList<String>();
for (int i = 0; i < count; i++) {
list.add(result[i]);
}
}
you are trying to create a List<String> result
variable despite there being a parameter called result
, so you'll need to rename it.尽管有一个名为
result
的参数,但您仍在尝试创建一个List<String> result
变量,因此您需要重命名它。 You also need to initialise your list outside of the loop to do what you want, eg:您还需要在循环之外初始化您的列表以执行您想要的操作,例如:
List<String> resultList = new ArrayList<String>();
for(int i=0; i<result.length; i++){
resultList.add(result[i]);
}
EDIT编辑
If you want to create multiple lists then you'll need to define a collection of type List<String>
, eg:如果你想创建多个列表,那么你需要定义一个
List<String>
类型的集合,例如:
List<List<String>> resultList = new ArrayList<List<String>>();
for(int i=0; i<result.length; i++){
resultList.add(new ArrayList<String>());
}
You can directly convert your String Array to ArrayList using this您可以使用此直接将字符串数组转换为 ArrayList
List<String> list = new ArrayList<String>(Arrays.asList(yourStringArray))
Thanks.谢谢。 Hope it will help.
希望它会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.