集合框架03

三、增强for循环(foreach)

1 //好处:代码少,方便遍历
2 //弊端:没有索引,不能操作容器里的元素
3 private static void function() {
4     int[] arr = {3,1,4,5,6};
5     for(int i:arr){
6         System.out.println(i);
7     }
8 }

四、泛型

   /*
 2  * JDK1.5 出现新的安全机制,保证程序的安全性
 3  *   泛型: 指明了集合中存储数据的类型  <数据类型>
 4  */
 5 
 6 public class GenericDemo {
 7     public static void main(String[] args) {
 8         function();
 9     }
10     
11     public static void function(){
12         Collection<String> coll = new ArrayList<String>();
13         coll.add("abc");
14         coll.add("rtyg");
15         coll.add("43rt5yhju");
16 //        coll.add(1);
17         
18         Iterator<String> it = coll.iterator();
19         while(it.hasNext()){
20             String s = it.next();
21             System.out.println(s.length());
22         }
23     }
24 }
/*
 *  带有泛型的接口
 *  
 *  public interface List <E>{
 *    abstract boolean add(E e);
 *  }
 *  实现类,先实现接口,不理会泛型
 *  public class ArrayList<E> implements List<E>{
 *  }
 *  调用者 : new ArrayList<String>() 后期创建集合对象的时候,指定数据类型
 *  
 *  实现类,实现接口的同时,也指定了数据类型
 *  public class XXX implements List<String>{
 *  }
 *  new XXX()
 */
 1 /*
 2  *  泛型的通配符
 3  */
 4 public class GenericDemo {
 5     public static void main(String[] args) {
 6         ArrayList<String> array = new ArrayList<String>();
 7         
 8         HashSet<Integer> set = new HashSet<Integer>();
 9         
10         array.add("123");
11         array.add("456");
12         
13         set.add(789);
14         set.add(890);
15         
16         iterator(array);
17         iterator(set);
18     }
19     /*
20      *  定义方法,可以同时迭代2个集合
21      *  参数: 怎么实现 , 不能写ArrayList,也不能写HashSet
22      *  参数: 或者共同实现的接口
23      *  泛型的通配,匹配所有的数据类型  ?
24      */
25     public static void iterator(Collection<?> coll){
26         Iterator<?> it = coll.iterator();
27         while(it.hasNext()){
28             //it.next()获取的对象,什么类型
29             System.out.println(it.next());
30         }
31     }
32 } 

转载于:https://www.cnblogs.com/Nelsoner/p/6677685.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值