Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Class not compiling  RSS feed

 
Brenda Stevens
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

When i try to compile this code it says cannot find symbol- iterator(). im slightly confused as to why it wont compile. I have all the java packages at the top of the class in which i am trying to compile the code in. This is similar code in which i have previously used for another method. Im not sure if i have made a mistake but i just havent been able to spot it. Any help will be most grateful
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What type of object is allChampions? You haven't included the declaration for that. That's where the issue will be - it has to be of a class that has an iterator() method for you to be able to call the method.
 
Brenda Stevens
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
allChampions is a HashMap. I looked in java class libraries but couldn't see this method in there
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There you go then.

A HashMap contains key/value pairs, so it's not clear what an iterator() method would give you, which is why it doesn't exist. There are three ways of getting an Iterator out of a Map:

- To iterate across the keys, use map.keySet().iterator() (as the name suggests, keySet() gives you a Set containing all the keys)

- To iterate across the values, use map.values().iterator()

- To iterate across each pair in turn (which is the most efficient approach if you need to access the key and value at the same time), use map.entrySet().iterator() (entrySet() returns a Set of Map.Entry objects, which hold the key and value together)


Are your Champions objects the keys or the values? That will determine which you should use.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!