Win a copy of Getting started with Java on the Raspberry Pi this week in the Raspberry Pi forum!
  • 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Liutauras Vilda
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Piet Souris

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). . .
 
Be reasonable. You can't destroy everything. Where would you sit? How would you read a tiny ad?
Low Tech Laboratory
https://www.kickstarter.com/projects/paulwheaton/low-tech-0
reply
    Bookmark Topic Watch Topic
  • New Topic