集合中的泛型不作为重点讲解 直接上代码,代码的解释都在注释中给出
1 package com.shsxt.lisa; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 6 /* 7 * 泛型 8 * jdk1.5 新的安全机制 保证程序的安全性 9 * 10 * 指明了集合中储存数据的类型<数据类型> 11 * 12 * 带有泛型的接口 13 * public interface List<E>{ 14 * abstract boolean add(E e); 15 * } 16 * 第一种: 17 * 实现类 先实现接口 不理会泛型 18 * public class ArrayList<E> implements List<E>{} 19 * 第二种: 20 * 实现类实现接口的同时知道数据类型 21 * public class XXX implements List<String>{ 22 * 23 * } 24 * 25 */ 26 public class GenericDemo { 27 28 public static void main(String[] args) { 29 function(); 30 } 31 32 public static void function(){ 33 34 ArrayList<Integer> array=new ArrayList<>(); 35 array.add(123); 36 array.add(345); 37 38 int[] arr={1,3,5}; 39 Integer[] newArr=new Integer[array.size()]; 40 /* 41 * ArrayList的toArray(T[] T) 42 * toArray()方法 可以将arraylist转成数组 43 */ 44 Integer[] array2 = array.toArray(newArr); 45 46 for(int i:array2){ 47 System.out.println(i); 48 } 49 50 } 51 }
1 /* 2 使用泛型的好处: 3 4 * 5 */ 6 public class GenericDemo2 { 7 8 public static void main(String[] args) { 9 10 List<String> list=new ArrayList<>(); 11 list.add("abc"); 12 list.add("def"); 13 //list.add(5);// 14 //集合已经明确具体存放的元素类型 那么在使用迭代器的时候,迭代器也会知道具体的元素类型 15 16 Iterator it=list.iterator(); 17 while(it.hasNext()){ 18 System.out.println(it.next()); 19 } 20 21 } 22 }
1 package com.shsxt.lisa; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 import java.util.HashSet; 6 import java.util.Iterator; 7 8 /* 9 * 泛型的通配符 10 */ 11 public class GenericDemo3 { 12 13 public static void main(String[] args) { 14 ArrayList<String> arr=new ArrayList(); 15 16 HashSet<Integer> hashSet = new HashSet<Integer>(); 17 18 arr.add("张二狗"); 19 arr.add("元首"); 20 21 hashSet.add(12); 22 hashSet.add(34); 23 24 iterator(arr); 25 } 26 27 28 /* 29 * 定义方法 可以同时迭代2个集合 30 * 31 * 泛型的通配符: 32 * ? 匹配所有的数据类型 33 */ 34 35 public static void iterator(Collection<?> e){ 36 Iterator it=e.iterator(); 37 while(it.hasNext()){ 38 /* 39 * it.next()此处的类型已经是Object 所以一定不要强转 40 */ 41 System.out.println(it.next()); 42 } 43 } 44 45 }