Java基础(12)- Java泛型

Java泛型详解与应用

目录

1 为什么引入泛型?

2 泛型类

2.1 声明泛型类

2.2 传递多个参数的泛型

3 类型参数的约束

4 类型安全

5 泛型方法

5.1 打印任意类型的方法

5.2 限制打印方法

5.3 传入多个参数

6 通配符?

1 为什么引入泛型?

如果我们想要一个类负责实例化对象,并且有一个方法可以打印该对象的值

//负责打印的类
  public class IntegerPrinter {
    Integer content;

    IntegerPrinter(Integer content) {
      this.content = content;
    }

    public void print() {
      System.out.println(content);
    }
  }
//主程序
public class Main {
	public static void main(String[] args) {
		IntegerPrinter printer = new IntegerPrinter(123);
		printer.print();
	}
}

运行程序后, 一切正常

但是如果想打印 字符串 类型,那么我们需要重新创建一个 负责打印字符串 的类

2 泛型类

2.1 声明泛型类

在类名后加上 <T> <>里面可以是任何东西

public class Printer<T> { }

public class Printer<T> {
	T content;
    Printer(T content) {
        this.content = content;
    }
    
    public void print() {
        System.out.println(content);
    }
}
//主程序
public class Main {
	public static void main(String[] args) {
		Printer<Integer> printer = new Printer<>(123); //<>中的类型必须是包装过的类,不能用基本数据类型
        printer.print();
        
        Printer<String> printer = new Printer<>("hello world"); //<>中的类型必须是包装过的类,不能用基本数据类型
        printer.print();
	}
}

2.2 传递多个参数的泛型

public class Printer<T,K> {
	T content;
	K content2;
    Printer(T content,K content2) {
        this.content = content;
        this.content2 = content2;
    }
    
    public void print() {
        System.out.println(content);
        System.out.println(content2);
    }
}

//主程序
public class Main {
	public static void main(String[] args) {
        //<>中的类型必须是包装过的类,不能用基本数据类型
		Printer<String, Integer> printer = new Printer<>("hello world",123); 
        printer.print();
	}
}

3 类型参数的约束

public class Printer<T extends Father>

这样传进去的参数就只能是继承的内容。

public class Printer<T extends FatherClass & ImplementClass>

这样可以扩大到实现的接口类。

4 类型安全

向List里面随意放元素,在获取的时候会发生类型错误。

5 泛型方法

5.1 打印任意类型的方法

print("hello");
print(123);
print(12L);
print(new Class());

private static <T> void print(T content) {
	System.out.println(content);
}

5.2 限制打印方法

private static <T extends Vehicle & Thing> void print(T content) {
	System.out.println(content);
}

5.3 传入多个参数

private static <T , K> void print(T content,K content2) {
	System.out.println(content);
	System.out.println(content2);
}

6 通配符?

<> 中放入 ? 即可

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值