• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ArrayList confusion

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could someone shed some light on the ArrayList below.





I thought this would print

This is ClassA
This is ClassA
This is ClassA


Error
ClassB.java:11: incompatible types
found : ClassA
required: java.lang.String
for (String inList : myList) {
 
Phil Dixon
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Changed this line to



And now get

ClassA@82ba41
ClassA@923e30
ClassA@130c19b
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


for (String inList : myList) {
System.out.println(inList);
}




Error
ClassB.java:11: incompatible types
found : ClassA
required: java.lang.String
for (String inList : myList) { ...


Well as you can see in the error message it says found ClassA required String for (String inList : myList).

So the code state that in the List called myList each element will be a String But this is not true because it is declared as a ArrayList of ClassA : .

In conclusion the solution is to do :
as the compiler told you.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Note that you're printing "This is ClassA" from the constructor of ClassA. This code as written should indeed print "This is ClassA" 3 times, but it's not working the way I think you think it's working. Think about what is actually happening when you say System.out.println(inList). . .
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic