wood burning stoves*
The moose likes Beginning Java and the fly likes ArrayList confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ArrayList confusion" Watch "ArrayList confusion" New topic
Author

ArrayList confusion

Phil Dixon
Greenhorn

Joined: Aug 13, 2005
Posts: 11
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

Joined: Aug 13, 2005
Posts: 11
Changed this line to



And now get

ClassA@82ba41
ClassA@923e30
ClassA@130c19b
Julien Grenier
Ranch Hand

Joined: Sep 01, 2005
Posts: 41

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.
Tommy Becker
Greenhorn

Joined: Sep 22, 2005
Posts: 8
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). . .
 
Don't get me started about those stupid light bulbs.
 
subject: ArrayList confusion
 
Similar Threads
remove the element in list while iterating through it.
Using asList with Generics
compareTo()
Generics
Generics Problem