【问题标题】:Iterate through items in arraylist, with an index使用索引遍历数组列表中的项目
【发布时间】:2014-01-01 15:24:16
【问题描述】:

我想遍历对象数组列表中的项目,以及索引,以便我可以将字符串(对象/类的一部分)传输到ArrayList<String>

我的代码:

for(PeopleDetails person : people_list; /*not using termination, will terminate at end of people_list */ ;i++){
  /// Code here         
}

但是我得到一个错误,说:

Type mismatch: cannot convert from ArrayList<PeopleDetails> to PeopleDetails.

是什么导致了这个错误? 感谢您的帮助!

【问题讨论】:

  • 它告诉你people_listArrayList 而不是PeopleDetails
  • 你是如何声明你的ArrayList的?
  • 尝试发布更多相关的代码,如数量明智。另外,为什么不使用普通的 for 循环而不是 增强的 循环呢?

标签: java android loops arraylist


【解决方案1】:

这不是for-each 声明(为清楚起见,我删除了您的评论):-

for(PeopleDetails person : people_list;  ;i++)

这是:-

for(PeopleDetails person : people_list)

您将其用作for 语句。如果您想在for-each 中保留索引,则需要手动进行:-

 int index = 0;
 for(PeopleDetails person : people_list)
 {
   index++;
 }

进一步讨论使用索引can be found here 遍历集合的其他方法。

【讨论】:

  • 是的,后来我意识到了这一点。因此这个问题是没用的......我怎样才能删除它???
  • 不需要删除
  • 这个网站的目的是让其他人搜索问题,这可能会再次出现。
  • 好的,我就不说了。
【解决方案2】:

如果您的List people_list 属于String,请尝试

ArrayList<String>people_list = new ArrayList<String>(); 
for(String i :people_list){
    //Code
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多