有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用索引遍历arraylist中的项

我想迭代对象的arraylist中的项,并使用索引,以便将字符串(对象/类的一部分)转换为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

是什么导致了这个错误? 谢谢你的帮助


共 (2) 个答案

  1. # 1 楼答案

    如果你的Listpeople_list属于String,那么试试看

    ArrayList<String>people_list = new ArrayList<String>(); 
    for(String i :people_list){
        //Code
    }
    
  2. # 2 楼答案

    这不是一个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遍历集合的其他方法