• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem: ArrayList with For loop  RSS feed

 
Faisal Fuad
Ranch Hand
Posts: 88
IBM DB2 Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi...please help me to find my mistake. Two cups of coffee are still not enough for this boring time (4:51 PM-Friday)



Compiler is showing red under myArrayList in the above for loop....and saying "Type mismatch: cannot convert from element type Object to String"

Thanks
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Faisal Fuad wrote:
Compiler is showing red under myArrayList in the above for loop....and saying "Type mismatch: cannot convert from element type Object to String"


You didn't say which occurrence of myArrayList it's complaining about, but I'm feeling generous so I'll break out my crystal ball and predict that it's this one:



Since you didn't use generics to say that it's a list of Strings, i.e.:


the compiler takes it as a list of Object, so an Iterator (which is what the foreach loop uses) will give you back objects.

You have to either use generics, or cast in your loop.

Or, since your loop doesn't actually use any String-only methods, just treat them as objects throughout your loop.
 
Faisal Fuad
Ranch Hand
Posts: 88
IBM DB2 Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I told you Jeff...this is Friday Afternoon man Oh...!!! Thanks a lot....the problem is solved. Have a great weekends...
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeff was faster than me, so I'd just offer two useful links you won't be sorry to read: Generics tutorial, Collections Framework tutorial.
 
Faisal Fuad
Ranch Hand
Posts: 88
IBM DB2 Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Martin...I already took those two links into my backpack for next two days. Promise will finish them all Have a good one.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!