keySet()问题!

Edwin603 2009-07-02 11:00:55
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()肯定是用不了的 因为他不能出对象 那上面那个是怎么回事

...全文
185 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Edwin603 2009-07-02
  • 打赏
  • 举报
回复
谢谢楼上 明白!
knightzhuwei 2009-07-02
  • 打赏
  • 举报
回复
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()));
}
Edwin603 2009-07-02
  • 打赏
  • 举报
回复
是啊 我也这么理解 但是 返回哪个以Set为父类的对象呢?
HashSet? 不可能 我试验过
那又是什么呢 难道返回一个 API里 没有的子类对象吗?
不可能啊 很迷茫 继续求教!
bigbug9002 2009-07-02
  • 打赏
  • 举报
回复
Set <String> s = new Set <String>(); 不能这样,编译会出错的.

你可以理解为keySet()方法返回一个以Set为父类的对象.

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧