- 泛型
- 对象的定义
类名称<具体类> 对象名称 = new 类名称<具体类> ();
class Point<T>{ T可以是任意的字母
private T value; //封装
public T getValue(){ //同类型
return value;
}
public void setValue(T value){
this.value=value;
}
}
class ListSetMap {
public static void main(String[] args) {
Point<String> a=new Point<String>(); //String可以改成其他类型
a.setValue("一些人");
System.out.println(a.getValue());
}
}
注意:已经指定的泛型是不能够将其变量的类型改为其他类型;
- 泛型也有构造方法
- 可以设置多个泛型类型
class Point<T,K>{
private T value1;
private K value2;
public Point(T value1,K value2){
this.value1=value1;
this.value2=value2;
}
public T getValue1(){
return value1;
}
public K getValue2(){
return value2;
}
}
class ListSetMap {
public static void main(String[] args) {
Point<Integer,String> a=new Point<Integer,String>(1,"嘿嘿");
System.out.println(a.getValue1()+"\n"+a.getValue2());
}
}
输出 1
嘿嘿
- 通配符
在接收任意的对象时,不会对象是什么类型,就可以用Point<?> t来接收Point的对象
class Point<T>{
private T value1;
public Point(T value1){
this.value1=value1;
}
public T getValue1(){
return value1;
}
}
class ListSetMap {
public static void main(String[] args) {
Point<String> a= new Point<String>("a");
fun(a);
}
public static void fun(Point<?> t){
System.out.println(t.getValue1());
}
}
- 受限泛型
class ListSetMap {
public static void main(String[] args) {
Point<String> a=new Point<String>("a");
//fun(a); //不能被接收
fun2(a);
Point<Integer>b =new Point<Integer>(1);
fun(b);
//fun2(b); //不能被接收
}
public static void fun(Point<? extends Number> t){
System.out.println(t.getValue1());
}
public static void fun2(Point<? super String> t){
System.out.println(t.getValue1());
}
}
输出 a
1
- 泛型不能向上转型
class ListSetMap {
public static void main(String[] args) {
Point<String> a=new Point<String>("a");
Point<Object> b=null;
b=a;
}
public static void fun(Point<? extends Number> t){
System.out.println(t.getValue1());
}
}
输出ListSetMap.java:15: 错误: 不兼容的类型: Point<String>无法转换为Point<Object>
- 通过泛型方法返回泛型类实例
class ListSetMap {
public static void main(String[] args) {
Point<Integer> a=fun(10); //fun(10)会返回一个实例
System.out.println(a.getValue1());
}
public static <T extends Number> Point<T> fun(T t){
Point<T> temp=new Point<T>(); //实例化
temp.setValue1(t);
return temp; //返回实例-(对象)
}
}
输出 10
- 泛型数组
class ListSetMap {
public static void main(String[] args) {
Integer i[]=fun1(1,2,3,4,5);
fun2(i);
}
public static <T>T[] fun1(T...arg){ //接收可变参数
return arg; //返回类型<T> T[]的
}
public static <T> void fun2(T p[]){
for(T t : p)
System.out.println(t);
}
}
- 嵌套泛型类
class Point<T>{
private T value1;
public Point(T value1){
this.value1=value1;
}
public T getValue1(){
return value1;
}
public void setValue1(T value1){
this.value1=value1;
}
}
class Demo<S>{
private S info;
public Demo(S s){
this.info=s;
}
public void setInfo(S info){
this.info=info;
}
public S getInfo(){
return info;
}
}
class ListSetMap {
public static void main(String[] args) {
Demo<Point<String>> a=null; //将Point作为Demo的泛型类型
Point<String> b=new Point<String>("嵌入类"); //实例化
a=new Demo<Point<String>>(b);
System.out.println(a.getInfo().getValue1()); //调用info
info=Point<String
}
}