JAVA 泛型与foreach循环

泛型

泛型是编译期有效,在运行期会被擦除。
为什么要引入泛型?
	集合中可以放不同类型的元素,确实很方便,但是当我们遍历集合时,就会遇到一个问题,数据类型会以Object类传入,不同类型的元素有着不同的方法,那么我们在遍历的时候如果要求调用这些方法,就不得不用Object类进行大量的强制类型转换使不同的元素可以调用不同的方法,所以出现新特性,引入泛型。
泛型的作用:
	统一集合中的元素类型
	减少遍历时的强制类型转换
泛型是用来规定一个集合只能存储这一类的元素,在遍历的时候再次使用泛型就不用进行强制类型转换。
泛型的优点与缺点:
	优点:集合类型统一,减少强制类型转换
	缺点:集合只能存储一种数据类型的元素
泛型的格式:<数据类型> 该数据类型只能是引用数据类型
	ArrayList存储对象进行泛型遍历
 public static void main(String[] args) {
        Student s1=new Student("张三",15);
        Student s2=new Student("李四",15);
        Student s3=new Student("王五",15);
        //集合使用泛型用来存储Student类型元素
        Collection<Student> a=new ArrayList();
        a.add(s1);
        a.add(s2);
        a.add(s3);
        //迭代器用来迭代Student元素,就不用进行强制类型转换,直接可调用Student中的toString方法
        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,....>泛型类型必须是引用类型
//创建泛型类,在泛型类里面T就是相当于类,创建对象的时候传入T为String,类里面的T就都是String
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();//返回传入参数的数据类型String
        fanxingTest<Integer> fx1=new fanxingTest<>(121);
        fx1.A();//返回传入参数的数据类型Integer
    }
}
泛型方法
定义:把泛型定义在方法上
格式: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);//泛型方法20.0
        fun(20);//int20
        fun("20");//String20
    }
}
泛型通配符
泛型通配符<?>	类型没有明确,任意类型
<? 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>() ;
	//Animal是Dog的父类,<? extends E>表示向下限定
	Collection<? extends Animal> col9 = new ArrayList<Object>() ;//错误
	Collection<? extends Animal> col10 = new ArrayList<Animal>() ;
	Collection<? extends Animal> col11 = new ArrayList<Dog>() ;
	//object类是所有类的父类,<? super E>
	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("=========");
        //使用foreach
        for (int e:a) {//int e 代表的是集合或者数组中的每一个元素
            System.out.println(e);
        }
        System.out.println("=============");
        //集合 需要用泛型,类型统一,才可以用foreach
        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 (int i = 0; i <ins.length ; i++) {
            if(i==ins.length-1){
                sb.append(ins[i]);
            }else {
                sb.append(ins[i]);
                sb.append(",");
            }
        }

         */
        //以上循环不适合使用foreach
        for (String s:ins) {
            sb.append(s);
            sb.append(",");
        }
        //这样会在最后一个元素后面也出现",",就必须截取掉
        //截取逗号
        System.out.println(sb.substring(0,sb.length()-1));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值