java基础——泛型
泛型的引入看下面这段代码:
private static int add(int a, int b) {
System.out.println(a + "+" + b + "=" + (a + b));
return a + b;
}
private static float add(float a, float b) {
System.out.println(a + "+" + b + "=" + (a + b));
return a + b;
}
private static double add(double a, double b) {
System.out.println(a + "+" + b + "=" + (a + b));
return a + b;
}如果没有泛型,要实现不同类型的加法,每种类型都需要重载一个add方法;通过泛型,我们可以复用为一个方法:
private static <T extends Number> double add(T a, T b) {
System.out.println(a + "+" + b + "=" + (a.doubleValue() + b.doubleValue()));
return a.doubleValue() + b.doubleValue();
}泛型中的类型在使用时指定,不需要强制类型转换(类型安全,编译器会检查类型)
下面这段代码:
List list = new ArrayList();
list.add("xxString");
list.add(100d);
list.add(new Person());我们在使用上述list中,list中的元素都是Object类型(无法约束其中的类型),所以在取出集合元素时需要人为的强制类型转化到具体的目标类型,且很容易出java.lang.ClassCastException`异常。
引入泛型,它将提供类型的约束,提供编译前的检查:
List<String> list = new ArrayList<String>();
// list中只能放String, 不能放其它类型的元素泛型的好处
1、编译时,检查添加元素的类型,提高了安全性
2、减少了类型转换的次数,提高效率
3、不再提示编译警告
介绍
1.泛型又称参数化类型,是Jdk5.0出现的新特性,解决数据类型的安全性问题
2.在类声明或实例化时只要指定好需要的具体的类型即可。
3.Java泛型可以保证如果程序在编译时没有发出警告,运行时就不会产生ClassCastException.异常。同时,代码更加简洁、健壮
4.泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,或者是某个方法的返回值的类型,或者是参数类型。
代码举例:
public class Generic03 {
public static void main(String[] args) {
//注意,特别强调:E具体的数据类型在定义Person对象的时候指定,即在编译期间,就确定E是什么类型
Person<String> person = new Person<>("dfdfs");
person.show();//String
/**
* Person类相当于下面这样子
* class Person{
* String s;//E表示s的数据类型,该数据类型在定义Person对象的时候指定,即在编译期间,就确定E是什么类型
*
* public Person(String s) {//E也可以是参数类型
* this.s = s;
* }
*
* public String f(){//返回类型使用E
* return s;
* }
* public void show(){
* System.out.println(s.getClass());//显示s的运行类型
* }
* }
*/
Person<Integer> person2 = new Person<>(100);
person2.show();
/**
* Person类相当于下面这样子
* class Person{
* Integer s;//E表示s的数据类型,该数据类型在定义Person对象的时候指定,即在编译期间,就确定E是什么类型
*
* public Person(Integer s) {//E也可以是参数类型
* this.s = s;
* }
*
* public Integer f(){//返回类型使用E
* return s;
* }
* public void show(){
* System.out.println(s.getClass());//显示s的运行类型
* }
* }
*/
}
}
//泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,或者是某个方法的返回值的类型,或者是参数类型
class Person<E>{
E s;//E表示s的数据类型,该数据类型在定义Person对象的时候指定,即在编译期间,就确定E是什么类型
public Person(E s) {//E也可以是参数类型
this.s = s;
}
public E f(){//返回类型使用E
return s;
}
public void show(){
System.out.println(s.getClass());//显示s的运行类型
}
}语法
泛型的声明
interface 接口名<T,R....>{
}和class 类名{}
说明:
1)其中,T,K,V不代表值,而是表示类型
2)任意字母都可以。常用T表示,是Type的缩写
泛型的实例化
要在类名后面指定类型参数的值(类型)。如:
List<String> strList = new ArrayList<String>();
Iterator<Customer> iterator = customers.iterator();泛型使用举例
需求:
1.创建3个学生对象
2.放入到HashSet中学生对象,使用.
3.放入到HashMap中,要求Key 是String name,Value就是学生对象
4.使用两种方式遍历
public class GenericExercise {
public static void main(String[] args) {
//使用泛型方式给HashSet放入3个学生对象
HashSet<Student> students = new HashSet<>();
students.add(new Student("jack",18));
students.add(new Student("tom",18));
students.add(new Student("ml",18));
//第一种遍历方式,增强for循环
for (Student student:students){
System.out.println(student);
}
//使用泛型方式给HashMap放入3个学生对象
HashMap<String, Student> hm = new HashMap<>();
hm.put("milan",new Student("milan",34));
hm.put("jack",new Student("jack",31));
hm.put("tom",new Student("tom",30));
//2.迭代器
Set<Map.Entry<String, Student>> entries = hm.entrySet();
Iterator<Map.Entry<String, Student>> iterator = entries.iterator();
System.out.println("==========================");
while (iterator.hasNext()){
Map.Entry<String, Student> next = iterator.next();
System.out.println(next.getKey()+"-"+next.getValue());
}
}
}
class Student{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}泛型使用注意事项
1.interface 接口名<T,R....>{
}和class 类名中T,K,V只能是引用类型。如下面:
List<Integer> list = new ArrayList<Integer>();//这样写正确
List<int> list = new ArrayList<int>();//这样写错误2.在给泛型指定具体类型后,可以传入该类型或者其子类类型
3.泛型使用形式
//1.第一种方式
List<Integer> list1 = new ArrayList<Integer>();
//2.第二种方式
List<Integer> Iist2 = new ArrayList<>();
3.如果我们这样写List list3=new ArrayList();默认给它的泛型是E就是Object.,等价于ArrayList arrayList = new ArrayList();
自定义泛型
自定义泛型类
语法:
class 类名<T,R....>{//......表示可以有多个泛型
成员
}注意事项:
1.普通成员可以使用泛型(属性、方法)
2.使用泛型的数组,不能初始化
3.静态方法中不能使用类的泛型
4.泛型类的类型,是在创建对象时确定的(因为创建对象时,需要指定确定类型)
5.如果在创建对象时,没有指定类型,默认为Object
class Tiger<T,R,M>{
String name;
R r;//属性使用到泛型
M m;
T t;
T[] ts;//因为数组在new时不能确定T的类型,就无法在内存开空间
public Tiger(String name) {
this.name = name;
}
public Tiger(R r, M m, T t) {
this.r = r;
this.m = m;
this.t = t;
}
public Tiger(String name, R r, M m, T t) {//构造器使用泛型
this.name = name;
this.r = r;
this.m = m;
this.t = t;
}
//因为静态是和类相关的,在类加载时,对象还没有创建
//所以,如果静态方法和静态属性使用了泛型,JVM就无法完成初始化
//static R r2;
// public static void m1(M m){
//
// }
public R getR() {//返回类型可以使用泛型
return r;
}
public void setR(R r) {//方法使用到泛型
this.r = r;
}
}自定义泛型接口
语法:
interface 接口名<T,R....>{
}注意事项:
1.接口中,静态成员也不能使用泛型(这个和泛型类规定一样)
2.泛型接口的类型,在继承接口或者实现接口时确定
3.没有指定类型,默认为Object
/**
* 泛型接口使用的说明
* 1.接口中,静态成员也不能使用泛型
* 2.泛型接口的类型,在继承接口或者实现接口时确定
* 3.没有指定类型,默认为Object
*/
//在继承接口指定泛型接口的类型
interface IA extends IUsb<String,Double>{
}
//当我们去实现IA接口时,因为IA在继承IUsub接口时,指定了U为String, R为Double,在实现IUsub接口的方法时,使用String替换U,是Double替换R
class AA implements IA{
@Override
public Double get(String s) {
return null;
}
@Override
public void hi(Double aDouble) {
}
@Override
public void run(Double r1, Double r2, String u1, String u2) {
}
}
//实现接口时,直接指定泛型接口的类型
//给U指定Integer给R指定了Float
//所以,当我们实现IUsb方法时,会使用Integer替换U,使用Float替换R
class BB implements IUsb<Integer,Float>{
@Override
public Float get(Integer integer) {
return null;
}
@Override
public void hi(Float aFloat) {
}
@Override
public void run(Float r1, Float r2, Integer u1, Integer u2) {
}
}
//没有指定类型,默认为Object
//建议直接写成IUsb<Object,Object>
class CC implements IUsb{//等价class CC implements IUsb<Object,,Object>
@Override
public Object get(Object o) {
return null;
}
@Override
public void hi(Object o) {
}
@Override
public void run(Object r1, Object r2, Object u1, Object u2) {
}
}
interface IUsb<U,R>{
//普通方法中,可以使用接口泛型
R get(U u);
void hi(R r);
void run(R r1,R r2,U u1,U u2);
//在jdk8中,可以在接口中,使用默认方法,也是可以使用泛型
default R method(U u){
return null;
}
}自定义泛型方法
语法
修饰符 <T,R...>返回类型 方法名(参数列表){
}注意事项:
1.泛型方法,可以定义在普通类中,也可以定义在泛型类中
2.当泛型方法被调用时,类型会确定
3.public void eat(E e){},修饰符后设有eat方法不是泛型方法,而是使用了泛型
public class CustomMethodGeneric {
public static void main(String[] args) {
Car car = new Car();
car.fly("宝马",100);//当调用方法时,传入参数,编译器,就会确定类型
System.out.println("==================");
Fish<String, ArrayList> fish = new Fish<>();
fish.hello(new ArrayList(),11.3f);
}
}
//泛型方法,可以定义在普通类中,也可以定义在泛型类中
class Car{//普通类
public void run(){//普通方法
}
//泛型方法
//1.<T,R>就是泛型
//2.是提供给 fly使用的
public <T,R> void fly(T t,R r){//泛型方法
System.out.println(t.getClass());
System.out.println(r.getClass());
}
}
class Fish<T,R>{//泛型类
public <U,M> void eat(U u,M m){//泛型方法
}
//下面的这个hi方法不是泛型方法,是hi方法使用了类声明的泛型
public void hi(T t){
}
//泛型方法,可以使用类声明的泛型,也可以使用自己声明泛型
public <K> void hello(R r,K k){
System.out.println(r.getClass());
System.out.println(k.getClass());
}
}泛型的继承和通配符
说明:
1.泛型不具备继承性
2.:支持任意泛型类型
3.
页:
[1]