Weird keySet() behavior

H

hilz

Hi all.
I was running a simple test on a TreeMap and i ran into something weird. I
am sure there is something i misunderstand, but i don't know what it is.

here is what i did:

java.util.TreeMap t = new java.util.TreeMap();
java.util.Set keys = t.keySet();
System.out.println( "class=" + keys.getClass().toString() );

the last statement prints the following:
class=class java.util.TreeMap$1

This sounds weird, as i expect to get a Set and not a Map.
any comments?

thanks
hilz
 
C

Christophe Vanfleteren

hilz said:
Hi all.
I was running a simple test on a TreeMap and i ran into something weird. I
am sure there is something i misunderstand, but i don't know what it is.

here is what i did:

java.util.TreeMap t = new java.util.TreeMap();
java.util.Set keys = t.keySet();
System.out.println( "class=" + keys.getClass().toString() );

the last statement prints the following:
class=class java.util.TreeMap$1

This sounds weird, as i expect to get a Set and not a Map.
any comments?

thanks
hilz

Obviously, you are getting a Set back.
It's just that the Set implementation you get back is an anonymous inner
class of the TreeMap class (hence the $1 after the TreeMap).
 
F

Frank

hilz said:
java.util.TreeMap t = new java.util.TreeMap();
java.util.Set keys = t.keySet();
System.out.println( "class=" + keys.getClass().toString() );

the last statement prints the following:
class=class java.util.TreeMap$1

This sounds weird, as i expect to get a Set and not a Map.
any comments?

TreeMap$1 would be an anonymous inner class that implements the Set
interface.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top