-
泛型技术产生的背景
- 在泛型出来之前,程序员是通过object对象来存储任意值的集合,该方法在使用时,必须知道存储的类型,否组容易引起classcastexcption异常
-
泛型操作的实现
-
package com.iflytek.request.genericity; public class Genericity { public void point_Integer() { Point<Integer> point = new Point(); point.setX(1); point.setY(2); } public void point_String() { Point<String> point = new Point(); point.setX("1"); point.setY("2"); } public void name_String() { Name<String,Integer> name = new Name(); name.setF(10); name.setX("name"); } public class Name<T,F> { public T getX() { return x; } public void setX(T x) { this.x = x; } public F getF() { return f; } public void setF(F f) { this.f = f; } private T x; private F f; } public class Point<T> { private T x; public T getX() { return x; } public void setX(T x) { this.x = x; } public T getY() { return y; } public void setY(T y) { this.y = y; } private T y; } }
-
-
泛型接口定义及实现
-
public interface IGenericity<T>{ public void setValue(T t); } public class IMainGenericity implements IGenericity<Float> { @Override public void setValue(Float s) { } } public class Genericity { public void Imain() { IMainGenericity iGenericity = new IMainGenericity(); iGenericity.setValue((float) 1.0); } }
-
-
通配符的使用
-
泛型类名<? extends T> 或 泛型类名<? super T> 或 泛型类名<?>
? extends T:表示T或T的子类
? super T:表示T或T的父类
?:表示可以是任意类型
-
通配符主要了解向上向下的转型,只可获取,不可设置
-
备注:不同情境下使用字符的用意
E:Element,常在java的collection里,List<E>,set<E>,Iterator<E>
K,V:key,value,键值对map中使用
N:Number,数字
T:Type,类型如String,Integer,Float等等