Reputation: 399
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!!
Upvotes: 0
Views: 835
Reputation: 8246
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.
Upvotes: 2
Reputation: 6527
If your List
people_list
is of String
, Then Try
ArrayList<String>people_list = new ArrayList<String>();
for(String i :people_list){
//Code
}
Upvotes: 0