0

I want to iterate through items in an arraylist of objects, with an index as well, so that I can transfer a string (part of object/class) into an ArrayList<String>

My code:

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

However I get an error, saying :

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

What causes this error ? Thanks for the help!!

Alexis C.
  • 82,826
  • 18
  • 154
  • 166
Swedish Architect
  • 369
  • 1
  • 5
  • 21

2 Answers2

2

This is not a for-each statement (I've removed your comment for clarity):-

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

This is:-

for(PeopleDetails person : people_list)

You're using it like a for statement. If you want to keep an index in a for-each you need to do it manually:-

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

Further discussion of other ways to iterate over a collection with an index can be found here.

Community
  • 1
  • 1
Ross Drew
  • 7,575
  • 2
  • 36
  • 51
0

If your List people_list is of String, Then Try

ArrayList<String>people_list = new ArrayList<String>(); 
for(String i :people_list){
    //Code
}
Rakesh KR
  • 6,049
  • 5
  • 39
  • 49