java简介以及了解java(三三)

泛型方法的定义
把数组拷贝到集合时,数组的类型一定要和集合的泛型相同。
<...>定义泛型,其中的"..."一般用大写字母来代替,也就是泛型的命名,其实,在运行时会根据实际类型替换掉那个泛型。
需要泛型参数或返回值同时又是某个类的子类又是某个接口的实现类的时候,可以使用
<? extends Xxxx & Xxxx>这种写法,注意:接口类型要放在类的后面,且只能使用’&’符。
例:

public class Test{
<E> void copyArrayToList(E[] os,List<E> lst){
for(E o:os){
lst.add(o);
}
}
static <E extends Number> void copyArrayToList(E[] os,List<E> lst){
for(E o:os){
lst.add(o);
}
}
static<E extends Number & Comparable> void copyArrayToList(E[] os,List<E> lst){
for(E o:os){
lst.add(o);
}
}
}

 

受限泛型是指类型参数的取值范围是受到限制的。
extends关键字不仅仅可以用来声明类的继承关系, 也可以用来声明类型参数(type parameter)的受限关系。例如, 我们只需
要一个存放数字的列表, 包括整数(Long, Integer, Short), 实数(Double, Float), 不能用来存放其他类型, 例如字符串(String),
也就是说, 要把类型参数T的取值泛型限制在Number极其子类中.在这种情况下, 我们就可以使用extends关键字把类型参
数(type parameter)限制为数字
只能使用extends不能使用super,只能向下,不能向上。
注意:只有参数表中可以使用<?> ,定义泛型时用<E>
泛型类的定义
我们也可以在定义类型中使用泛型
注意:静态方法中不能使用类的泛型,因为泛型类是在创建对象的时候给定泛型。
例:
class MyClass<E>{
public void show(E a){
System.out.println(a);
}
public E get(){
return null;
}
}
受限泛型
class MyClass <E extends Number>{
public void show(E a){
}
}
泛型与异常
泛型参数在catch块中不允许出现,但是能用在方法的throws之后。例:
import java.io.*;
interface Executor<E extends Exception> {
void execute() throws E;
}
public class GenericExceptionTest {
public static void main(String args[]) {
try {
Executor<IOException> e = new Executor<IOException>() {
public void execute() throws IOException{

// code here that may throw an
// IOException or a subtype of
// IOException
}
};
e.execute();
} catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
}
泛型的一些局限型
catch不能使用泛型,在泛型集合中,不能用泛型创建对象,不允许使用泛型的对象。
不能实例化泛型
T t = new T(); //error
不能实例化泛型类型的数组
T[] ts= new T[10]; //编译错误
不能实例化泛型参数数
Pair<String>[] table = new Pair<String>(10); // ERROR
类的静态变量不能声明为类型参数类型
public class GenClass<T> {
private static T t; //编译错误
}
静态方法可以是泛型方法,但是不可以使用类的泛型。
泛型类不能继承自Throwable以及其子类
public GenExpection<T> extends Exception{} //编译错误
不能用于基础类型int等
Pair<double> //error
Pair<Double> //right

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值