13.2 使用泛型好处、类使用泛型、方法使用泛型、接口使用泛型、泛型通配符、泛型上限与下限、模拟斗地主发牌

想了解更多请查看java学习(idea版)

目录

泛型

使用泛型的好处

列:使用泛型和不使用泛型的区别练习

类使用泛型

列:类使用泛型

方法使用泛型

列:方法使用泛型练习

接口使用泛型

泛型通配符

列:泛型通配符练习

通配符高级使用----受限泛型

列:泛型上限与下限的练习

列:按照斗地主的规则,完成洗牌发牌的动作。 具体规则: 使用54张牌打乱顺序,三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌。


泛型

泛型:可以在类或方法中预支地使用未知的类型。

使用泛型的好处

  1. 将运行时期的ClassCastException,转移到了编译时期变成了编译失败。

  2. 避免了类型强转的麻烦。

列:使用泛型和不使用泛型的区别练习

  • 好处:
  • 1.避免了类型转换的麻烦,存储的是什么类型,取出的就是什么类型
  •  2.把运行期异常(代码运行之后会抛出的异常),提升到了编译期(写代码的时候会报错)
  •  弊端:泛型是什么类型,只能存储什么类型的数据
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo01Generic {
    public static void main(String[] args) throws Exception {
       // demo01();//不使用泛型 出现java.lang.ClassCastException异常
        demo02();//使用泛型

    }
    /*  2 创建集合对象,使用泛型
        好处:
            1.避免了类型转换的麻烦,存储的是什么类型,取出的就是什么类型
            2.把运行期异常(代码运行之后会抛出的异常),提升到了编译期(写代码的时候会报错)
         弊端:泛型是什么类型,只能存储什么类型的数据
     */
    private static void demo02() {
        Collection<String> coll=new ArrayList<>();
        coll.add("老赵");
        coll.add("老钱");
        coll.add("老孙");
        //创建迭代器对象
        Iterator<String> iterator = coll.iterator();//多态写法
        while (iterator.hasNext()){
            String next = iterator.next();
            System.out.println(next);
        }

    }

    /*1 创建集合不使用泛型
      好处:集合不使用泛型,默认的类型就是Object类型,可以存储任意类型的数据
      弊端:不安全,会引发异常
    */
    private static void demo01() throws Exception{
        Collection coll = new ArrayList();
        coll.add("你好");
        coll.add(1);
        Iterator it = coll.iterator();
        while (it.hasNext()) {
            Object item = it.next();
            System.out.println(item);
            String str=(String) item;//java.lang.ClassCastException:
            System.out.println(str);
        }
    }
}

类使用泛型

  1.     泛型是一个未知的数据类型,当我们不确定什么什么数据类型的时候,可以使用泛型
  2.     泛型可以接收任意的数据类型,可以使用Integer,String,Student...
  3.     创建对象的时候确定泛型的数据类型

格式:

修饰符 class 类名<代表泛型的变量> { }

列:类使用泛型

public class GenericClass<E> {
    private E name;
    public E getName() {
        return name;
    }
    public void setName(E name) {
        this.name = name;
    }
}

测试: 

public class Demo02GenericClass {
    public static void main(String[] args) {
        GenericClass<String> g1=new GenericClass<>();
        g1.setName("老赵");
        System.out.println(g1.getName());

        GenericClass<Integer> g2=new GenericClass<>();
        g2.setName(1);
        System.out.println(g2.getName());
    }
}

 结果:

方法使用泛型

  泛型定义在方法的修饰符和返回值类型之间,在调用方法的时候确定泛型的数据类型, 传递什么类型的参数,泛型就是什么类型

    格式:
        修饰符 <泛型> 返回值类型 方法名(参数列表(使用泛型)){
            方法体;
        }

列:方法使用泛型练习

public class GenericMethod {
    //含有泛型的方法
    public <M> void method(M m){
        System.out.println(m);
    }
    //含有泛型的静态方法
    public  static <Y> void methodStatic(Y y){
        System.out.println(y);
    }

}
    public static void main(String[] args) {
        //1 使用还有泛型的方法
        GenericMethod gm = new GenericMethod();
        gm.method(10);
        gm.method(20.00);
        gm.method("hello world");
        //2 使用还有泛型的静态方法
        GenericMethod.methodStatic(10);
        GenericMethod.methodStatic(10.3);

    }

结果: 

接口使用泛型

 接口使用泛型

public interface GenericInterface<N> {
    void method(N n);//抽象方法 省略了public abstract
}

接口实现类有两种方式实现泛型

//实现类不是泛型
public class GenericInterfaceImpl implements GenericInterface<String>{
    @Override
    public void method(String n) {
        System.out.println(n);
    }
}
//实现类是泛型
public class GenericInterfaceImpl2<M> implements GenericInterface<M> {
    @Override
    public void method(M m) {
        System.out.println(m);
    }
}

 测试

    public static void main(String[] args) {
        GenericInterface gi = new GenericInterfaceImpl();
        gi.method("aaa");

        //接口实现类也是泛型
        GenericInterface<Integer> g1=new GenericInterfaceImpl2<>();
        g1.method(17);
        GenericInterface<String> g2=new GenericInterfaceImpl2<>();
        g2.method("老鼠");
    }

结果:

泛型通配符

当使用泛型类或者接口时,传递的数据中,泛型类型不确定,可以通过通配符<?>表示。但是一旦使用泛型的通配符后,只能使用Object类中的共性方法,集合中元素自身方法无法使用。

泛型的通配符:不知道使用什么类型来接收方法的时候,此时可以使用?,?表示未知通配符

列:泛型通配符练习

public class Demo05Generic {
    public static void main(String[] args) {
        Collection<String> coll=new ArrayList<>();
        coll.add("老赵");
        coll.add("老钱");
        coll.add("老孙");
        Collection<Integer> c2=new ArrayList<>();
        c2.add(1);
        c2.add(3);
        c2.add(4);
        printArray(coll);
        System.out.println("-----------------------");
        printArray(c2);

    }
     public static void printArray(Collection<?> coll){
         Iterator<?> iterator = coll.iterator();
         while (iterator.hasNext()){
             Object next = iterator.next();
             System.out.println(next);
         }
     }
}

结果: 

通配符高级使用----受限泛型

    泛型的上限限定: ? extends E  代表使用的泛型只能是E类型的子类/本身
    泛型的下限限定: ? super E    代表使用的泛型只能是E类型的父类/本身

列:泛型上限与下限的练习

public class Demo06Generic {
    public static void main(String[] args) {
        Collection<Integer> list1 = new ArrayList<Integer>();
        Collection<String> list2 = new ArrayList<String>();
        Collection<Number> list3 = new ArrayList<Number>();
        Collection<Object> list4 = new ArrayList<Object>();

        getElement1(list1);
        //getElement1(list2);//报错
        getElement1(list3);
        //getElement1(list4);//报错

        //getElement2(list1);//报错
        //getElement2(list2);//报错
        getElement2(list3);
        getElement2(list4);

        /*
            类与类之间的继承关系
            Integer extends Number extends Object
            String extends Object
         */
    }

    // 泛型的上限:此时的泛型?,必须是Number类型或者Number类型的子类
    public static void getElement1(Collection<? extends Number> coll) {
    }

    // 泛型的下限:此时的泛型?,必须是Number类型或者Number类型的父类
    public static void getElement2(Collection<? super Number> coll) {
    }
}

列:按照斗地主的规则,完成洗牌发牌的动作。 具体规则: 使用54张牌打乱顺序,三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌。

public class DouDiZhu {
    public static void main(String[] args) {
        //1.准备牌 定义一个存储54张牌的ArrayList集合,泛型使用String
        List<String> poker = new ArrayList<>();
        //定义两个数组,一个数组存储牌的花色,一个数组存储牌的序号
        String[] colors = {"♠", "♥", "♣", "♦"};
        String[] numbers = { "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3","2", "A"};

        //2给集合中添加54个牌
        poker.add("大王");
        poker.add("小王");
        //循环嵌套遍历两个数组,组装52张牌
        for (String color : colors) {
            for (String number : numbers) {
                poker.add(color+number);
            }
        }
        //System.out.println(poker);

        /* 3.洗牌
            使用集合的工具类Collections中的方法  static void shuffle(List<?> list) 使用默认随机源对指定列表进行置换。
         */
        Collections.shuffle(poker);

        //4发牌 定义4个集合 存储玩家牌和底牌
        List<String> play01=new ArrayList<>();
        List<String> play02=new ArrayList<>();
        List<String> play03=new ArrayList<>();
        List<String> dipai=new ArrayList<>();
        for (int i = 0; i < poker.size(); i++) {
            String myPoke = poker.get(i);
            if(i>=50){
                dipai.add(myPoke);
            }else if (i%3==0){
                play01.add(myPoke);
            }else if (i%3==1){
                play02.add(myPoke);
            }else if (i%3==2){
                play03.add(myPoke);
            }
        }

        //5 看牌
        System.out.println("玩家1的牌:"+play01);
        System.out.println("玩家2的牌:"+play02);
        System.out.println("玩家3的牌:"+play03);
        System.out.println("底牌牌:"+dipai);
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值