• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

maxw-obj

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

泛型及其使用

泛型概述

在前面学习集合时,我们都知道集合中是可以存放任意对象的,只要把对象存储集合后,那么这时他们都会被提升成Object类型。当我们在取出每一个对象,并且进行相应的操作,这时必须采用类型转换。

大家观察下面代码:


public class GenericDemo {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add("abc");
coll.add("itcast");
coll.add(5);//由于集合没有做任何限定,任何类型都可以给其中存放
Iterator it = coll.iterator();
while(it.hasNext()){
//需要打印每个字符串的长度,就要把迭代出来的对象转成String类型
String str = (String) it.next();
System.out.println(str.length());
}
}
}

程序在运行时发生了问题java.lang.ClassCastException。 为什么会发生类型转换异常呢? 我们来分析下:由于集合中什么类型的元素都可以存储。导致取出时强转引发运行时 ClassCastException。 怎么来解决这个问题呢? Collection虽然可以存储各种对象,但实际上通常Collection只存储同一类型对象。例如都是存储字符串对象。因此在JDK5之后,新增了泛型(Generic)语法,让你在设计API时可以指定类或方法支持泛型,这样我们使用API的时候也变得更为简洁,并得到了编译时期的语法检查。

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

tips:一般在创建对象时,将未知的类型确定具体的类型。当没有指定泛型时,默认类型为Object类型。

使用泛型的好处

上一节只是讲解了泛型的引入,那么泛型带来了哪些好处呢?

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

  • 避免了类型强转的麻烦。

通过我们如下代码体验一下:


public class GenericDemo2 {
public static void main(String[] args) {
       Collection<String> list = new ArrayList<String>();
       list.add("abc");
       list.add("itcast");
       // list.add(5);//当集合明确类型后,存放类型不一致就会编译报错
       // 集合已经明确具体存放的元素类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素类型
       Iterator<String> it = list.iterator();
       while(it.hasNext()){
           String str = it.next();
           //当使用Iterator<String>控制元素类型后,就不需要强转了。获取到的元素直接就是String类型
           System.out.println(str.length());
      }
}
}

tips:泛型是数据类型的一部分,我们将类名与泛型合并一起看做数据类型。

泛型的定义与使用

我们在集合中会大量使用到泛型,这里来完整地学习泛型知识。

泛型,用来灵活地将数据类型应用到不同的类、方法、接口当中。将数据类型作为参数进行传递。

定义和使用含有泛型的类

定义格式:


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

例如,API中的ArrayList集合:

泛型在定义的时候不具体,使用的时候才变得具体。在使用的时候确定泛型的具体数据类型。


class ArrayList<E>{
   public boolean add(E e){ }
​
   public E get(int index){ }
  ....
}

使用泛型: 即什么时候确定泛型。

在创建对象的时候确定泛型

例如,ArrayList<String> list = new ArrayList<String>();

此时,变量E的值就是String类型,那么我们的类型就可以理解为:


class ArrayList<String>{
    public boolean add(String e){ }
​
    public String get(int index){ }
    ...
}

再例如,ArrayList<Integer> list = new ArrayList<Integer>();

此时,变量E的值就是Integer类型,那么我们的类型就可以理解为:


class ArrayList<Integer> {
    public boolean add(Integer e) { }
​
    public Integer get(int index) { }
    ...
}

含有泛型的方法

定义格式:


修饰符 <代表泛型的变量> 返回值类型 方法名(参数){ }

例如,


public class MyGenericMethod {  
   public <MVP> void show(MVP mvp) {
  System.out.println(mvp.getClass());
  }
   
   public <MVP> MVP show2(MVP mvp) {
  return mvp;
  }
}

调用方法时,确定泛型的类型


public class GenericMethodDemo {
   public static void main(String[] args) {
       // 创建对象
       MyGenericMethod mm = new MyGenericMethod();
       // 演示看方法提示
       mm.show("aaa");
       mm.show(123);
       mm.show(12.45);
  }
}

含有泛型的接口

定义格式:


修饰符 interface接口名<代表泛型的变量> { }

例如,

public interface MyGenericInterface<E>{
public abstract void add(E e);

public abstract E getE();  
}

使用格式:

1、定义类时确定泛型的类型

例如


public class MyImp1 implements MyGenericInterface<String> {
@Override
   public void add(String e) {
       // 省略...
  }
​
@Override
public String getE() {
return null;
}
}

此时,泛型E的值就是String类型。

2、始终不确定泛型的类型,直到创建对象时,确定泛型的类型

例如


public class MyImp2<E> implements MyGenericInterface<E> {
@Override
public void add(E e) {
      // 省略...
}
​
@Override
public E getE() {
return null;
}
}

确定泛型:

/*
* 使用
*/
public class GenericInterface {
   public static void main(String[] args) {
       MyImp2<String>  my = new MyImp2<String>();  
       my.add("aa");
  }
}

泛型通配符

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

通配符基本使用

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

此时只能接受数据,不能往该集合中存储数据。

举个例子大家理解使用即可:

public static void main(String[] args) {
   Collection<Intger> list1 = new ArrayList<Integer>();
   getElement(list1);
   Collection<String> list2 = new ArrayList<String>();
   getElement(list2);
}
public static void getElement(Collection<?> coll){}
//?代表可以接收任意类型

tips:泛型不存在继承关系 Collection<Object> list = new ArrayList<String>();这种是错误的。

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

之前设置泛型的时候,实际上是可以任意设置的,只要是类就可以设置。但是在JAVA的泛型中可以指定一个泛型的上限和下限。

泛型的上限:

  • 格式: 类型名称 <? extends 类 > 对象名称

  • 意义: 只能接收该类型及其子类

泛型的下限:

  • 格式: 类型名称 <? super 类 > 对象名称

  • 意义: 只能接收该类型及其父类型

比如:现已知Object类,String 类,Number类,Integer类,其中Number是Integer的父类


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>();
   
   getElement(list1);
   getElement(list2);//报错
   getElement(list3);
   getElement(list4);//报错
 
   getElement2(list1);//报错
   getElement2(list2);//报错
   getElement2(list3);
   getElement2(list4);
 
}
// 泛型的上限:此时的泛型?,必须是Number类型或者Number类型的子类
public static void getElement1(Collection<? extends Number> coll){}
// 泛型的下限:此时的泛型?,必须是Number类型或者Number类型的父类
public static void getElement2(Collection<? super Number> coll){}

posted on 2025-12-23 15:31  知识札记  阅读(1)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3