views:

214

answers:

7

I have a method that goes through the possible states in a board and stores them in a HashMap

void up(String str){
  int a = str.indexOf("0");
  if(a>2){
   String s = str.substring(0,a-3)+"0"+str.substring(a-2,a)+str.charAt(a-3)+str.substring(a+1);
   add(s,map.get(str)+1);
   if(s.equals("123456780")) {
    System.out.println("The solution is on the level  "+map.get(s)+" of the tree");

        //If I get here, I need to know the keys on the map
       // How can I store them and Iterate through them using 
      // map.keySet()?

   }
  }

}

I'm interested in the group of keys. What should I do to print them all?

HashSet t = map.keySet() is being rejected by the compiler as well as

LinkedHashSet t = map.keySet()
+1  A: 

Set t = map.ketSet()

The API does not specify what type of Set is returned.

You should try to declare variables as the interface rather than a particular implementation.

TofuBeer
A: 

Just

Set t = map.keySet();
bmargulies
+2  A: 

Use:

Set<MyGenericType> keySet = map.keySet();

Always try to specify the Interface type for collections returned by these methods. This way regardless of the actual implementation class of the Set returned by these methods (in your case map.keySet()) you would be ok. This way if the next release the jdk guys use a different implementation for the returned Set your code will still work.

map.keySet() returns a View on the Keys of the map. Making changes to this view results in changing the underlying map though those changes are limited. See the javadoc for Map:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet%28%29

Yousuf Haider
A: 

Unless you're using an older JDK, I think its a little cleaner to use generics when using the Collections classes.

So thats

Set<MyType> s = map.keySet();

And then if you just iterate through them, then you can use any kind of loop you'd like. But if you're going to be modifying the map based on this keySet, you you have to use the keySet's iterator.

goatlinks
A: 
for ( String key : map.keySet() ) { 
 System.out.println( key );
}
lemon
A: 

All that's guaranteed from keySet() is something that implements the interface Set. And that could possibly be some undocumented class like SecretHashSetKeys$foo, so just program to the interface Set.

I ran into this trying to get a view on a TreeSet, the return type ended up being TreeSet$3 on close examination.

mmsmatt
A: 
Map<String, String> someStrings = new HashMap<String, String>();
for(Map.Entry<String, String> entry : someStrings.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
}

This is how I like to iterate through Maps. If you specifically want just the keySet(), that answer is elsewhere on this page.

Droo