泛型---集合2


泛型的基本术语:
  以ArrayList<E>为例,<>念typeof
    .E为类型参数变量
     .ArrayList<Integer>中的Integer为实际类型参数
    .整个称为ArrayList<E>泛型类型
    .整个ArrayList<Integer>称为参数化的类型(ParameterizedType)

1.声明在类上的泛型(泛型类)在静态函数上是无效的,但是作用于所有的非静态的; 案例:反序
2,通配符:? :public void test(ArrayList<?> list){};
  注意:由于?指向的是一种不确定的类型,以为不能调用与类型相关的方法,例如add(),-------总而言之,就是方法()中带?的
        只能调用与类型无关的方法
  有限制的通配符:
       Collection<? extends Number> list:实例要为Number的孩子,放过来,super:实例为其父亲
  *****在使用泛型类的时候,可以对其孩子进行限定<T extends ...)多个用&连接
public <T> void test3(T[] arr){ int start=0; int end=arr.length-1; while(start<end){ T temp=arr[start]; arr[start]=arr[end]; arr[end]=temp; start++; end--; } } 案例:最后一种最好 反序@Test public void test1(){ List<String> list=new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); // Iterator<String> it=list.iterator(); while(it.hasNext()){ System.out.println(it.next()); } //foreach:增强for循环 for(String e:list){ System.out.println(e); } } @Test public void test2(){ HashMap<Integer,String> hm=new HashMap<>(); hm.put(1, "aac"); hm.put(2, "aa"); hm.put(3, "cc"); Set<Integer> set=hm.keySet(); Iterator<Integer> it=set.iterator(); while(it.hasNext()){ System.out.println(hm.get(it.next())); } //entrySet Set<Entry<Integer, String>> set2= hm.entrySet(); Iterator<Map.Entry<Integer,String>> i=set2.iterator(); while(i.hasNext()){ Map.Entry<Integer,String> entry=i.next(); System.out.println(entry.getValue()); } System.out.println("增强for循环"); //增强for循环-----》最好的 for(Map.Entry<Integer,String> e:hm.entrySet()){ System.out.println(e.getValue()); } } }

 

posted @ 2016-04-11 20:35  戒。  阅读(105)  评论(0编辑  收藏  举报