泛型
泛型是编译期有效,在运行期会被擦除。
为什么要引入泛型?
集合中可以放不同类型的元素,确实很方便,但是当我们遍历集合时,就会遇到一个问题,数据类型会以Object类传入,不同类型的元素有着不同的方法,那么我们在遍历的时候如果要求调用这些方法,就不得不用Object类进行大量的强制类型转换使不同的元素可以调用不同的方法,所以出现新特性,引入泛型。
泛型的作用:
统一集合中的元素类型
减少遍历时的强制类型转换
泛型是用来规定一个集合只能存储这一类的元素,在遍历的时候再次使用泛型就不用进行强制类型转换。
泛型的优点与缺点:
优点:集合类型统一,减少强制类型转换
缺点:集合只能存储一种数据类型的元素
泛型的格式:<数据类型> 该数据类型只能是引用数据类型
ArrayList存储对象进行泛型遍历
public static void main(String[] args) {
Student s1=new Student("张三",15);
Student s2=new Student("李四",15);
Student s3=new Student("王五",15);
Collection<Student> a=new ArrayList();
a.add(s1);
a.add(s2);
a.add(s3);
Iterator<Student> it=a.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
class Student {
String name;
int age;
public Student(String name,int age){
this.name=name;
this.age=age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
泛型类
定义:将泛型定义在类上
格式:public class 类名<泛型类型1,....>泛型类型必须是引用类型
public class fanxingTest<T> {
public T ob;
public fanxingTest(T ob){
this.ob=ob;
}
public void A(){
System.out.println(ob.getClass().getName());
}
public static void main(String[] args) {
fanxingTest<String> fx=new fanxingTest<String>("aaaa");
fx.A();
fanxingTest<Integer> fx1=new fanxingTest<>(121);
fx1.A();
}
}
泛型方法
定义:把泛型定义在方法上
格式:public<泛型类型> 返回类型 方法名(泛型类型 变量名)
public class fanxingTest<T> {
public static <T> void fun(T a){
System.out.println("泛型方法"+a);
}
public static void fun(String a){
System.out.println("String"+a);
}
public static void fun(int a){
System.out.println("int"+a);
}
public static void main(String[] args) {
fun(20.0);
fun(20);
fun("20");
}
}
泛型通配符
泛型通配符<?> 类型没有明确,任意类型
<? extends E> 向下限定,E及其子类
<? super E> 向上限定,E及其父类
泛型明确类型之后,要求两边的数据类型相同
Collection<Object> col1 = new ArrayList<Object>() ;
Collection<Object> col2 = new ArrayList<Animal>() ;
Collection<?> col5 = new ArrayList<Object>() ;
Collection<?> col6 = new ArrayList<Animal>() ;
Collection<? extends Animal> col9 = new ArrayList<Object>() ;
Collection<? extends Animal> col10 = new ArrayList<Animal>() ;
Collection<? extends Animal> col11 = new ArrayList<Dog>() ;
Collection<? super Animal> col13 = new ArrayList<Object>() ;
Collection<? super Animal> col14 = new ArrayList<Animal>() ;
Collection<? super Animal> col15 = new ArrayList<Dog>() ;
foreach循环
增强for循环
语法:
for(数据类型 变量名: 集合名/数组名){
语句;
}
集合要想使用增强for循环,就需要使用泛型来规定集合中的数据类型统一。
如果不使用泛型,就得需要用Object类型来定义集合中的元素。
缺点:
没有下标。
public static void main(String[] args) {
int[] a={1,2,25,36,45};
for (int i = 0; i <a.length ; i++) {
System.out.println(a[i]);
}
System.out.println("=========");
for (int e:a) {
System.out.println(e);
}
System.out.println("=============");
Set<String> strs=new HashSet<String>();
strs.add("Jack");
strs.add("Lucy");
strs.add("Taylor");
for (String name:strs) {
System.out.println(name);
}
String[] ins={"运动","音乐","美食","旅游"};
StringBuffer sb=new StringBuffer();
for (String s:ins) {
sb.append(s);
sb.append(",");
}
System.out.println(sb.substring(0,sb.length()-1));
}