import java.util.*;
public class HashMapTest {
public static void main (String [] args) {
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("zhangsan","sh");
hm.put("wangwu","fd");
hm.put("zhaoliu","hre");
hm.put("asi","gre");
hm.put("shabi","gre");
Set<String> hs = hm.keySet();
System.out.println(hs.size());


}
}
问下 keySet()那个方法 返回一个Set类的对象
可是Set是个接口 那怎么用呢
比如 Set<String> s = new Set<String>();
我往里面放几个String对象 
那s.size()肯定是用不了的 因为他不能出对象 那上面那个是怎么回事

解决方案 »

  1.   

     Set <String> s = new Set <String>(); 不能这样,编译会出错的.你可以理解为keySet()方法返回一个以Set为父类的对象.
      

  2.   

    是啊 我也这么理解 但是 返回哪个以Set为父类的对象呢?
    HashSet? 不可能 我试验过 
    那又是什么呢 难道返回一个 API里 没有的子类对象吗?
    不可能啊 很迷茫 继续求教!
      

  3.   

    import java.util.HashMap;
    import java.util.Set;public class HashMapTest {
        public static void main (String [] args) {
            HashMap<String,String> hm = new HashMap<String,String>();
            hm.put("zhangsan","sh");
            hm.put("wangwu","fd");
            hm.put("zhaoliu","hre");
            hm.put("asi","gre");
            hm.put("shabi","gre");
            Set<String> hs = hm.keySet();
            System.out.println(hs.getClass().getName());//加一句
            System.out.println(hs.size());      
        }
    }得到结果
    java.util.HashMap$KeySet
    5可见是HashMap里定义的内部类KeySet的对象KeySet源码:
     private final class KeySet extends AbstractSet<K> {
            public Iterator<K> iterator() {
                return newKeyIterator();
            }
            public int size() {
                return size;
            }
            public boolean contains(Object o) {
                return containsKey(o);
            }
            public boolean remove(Object o) {
                return HashMap.this.removeEntryForKey(o) != null;
            }
            public void clear() {
                HashMap.this.clear();
            }keySet方法源码
      public Set<K> keySet() {
            Set<K> ks = keySet;
            return (ks != null ? ks : (keySet = new KeySet()));
        }