黑马程序员技术交流社区

标题: 集合里泛型的一点疑惑 [打印本页]

作者: 陈琦    时间: 2012-10-14 10:35
标题: 集合里泛型的一点疑惑
  1. import java.util.*;
  2. class Demo
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.                 Map<String,String> m = new HashMap<String,String>();
  7.                 m.put("1","beijing");
  8.                 m.put("2","tianjin");
  9.                 m.put("3","hubei");
  10.                 Set s = m.keySet();
  11.           //Set<String> s = m.keySet();既然Map m已经制定了泛型,Set为什么要加泛型?
  12.                 Iterator it = s.iterator();
  13.           //Iterator it1<String> = s.iterator();还有这里
  14.                 while(it.hasNext()) {
  15.                         System.out.println(it.next());
  16.                 }
  17.         }
  18. }
复制代码

作者: 杨华东    时间: 2012-10-14 10:52
本帖最后由 杨华东 于 2012-10-14 10:53 编辑

跟你说   
1,set集合里泛型是不确定的 当然要指定一哈。
2,Iterator是set集合封装的内部类它要操作的元素与Set集合操作的元素必须一致,所以也要指定一哈。

你想想  被封装的内部类 总不会操作set集合以外的元素吧???简单的道理  希望你明白哈    加油
作者: 黄小贝    时间: 2012-10-14 12:31
public interface Map<K,V>  这是Map接口的声明~

/**
     * Returns a {@link Set} view of the keys contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation), the results of
     * the iteration are undefined.  The set supports element removal,
     * which removes the corresponding mapping from the map, via the
     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
     * operations.
     *
     * @return a set view of the keys contained in this map
     */
    Set<K> keySet();  //这是Map接口里面 keySet方法的声明


我觉得是否要写泛型只和函数的声明有关,函数返回值里面带了 <K>,如果不写泛型会有警告,但是不会报错。
而且~如果  Map<K,V>  泛型的 K 和  Set<K> keySet() 的 K 类型 不一致编译是不会过的~

下面的iterator是一个道理









欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2