什么使泛型?
为什么需要使用泛型?
package com.am.demo01;
/**
* @program: java高级-泛型
* @description:
* @author: 阿木
* @create: 2021-12-20 14:22
**/
public class Test01 {
public static void main(String[] args) {
Point p1=new Point(15,25);//值都是整数
Point p2=new Point(15.5,25.5);//值都是小数
Point p3=new Point("东经150度","北纬30度");//值都是字符串
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}
//思考: 我可以创建一个Point对象,而该对象在赋值时x坐标为整数,y坐标为字符串。这个程序会不会报错。【不会】
// 破坏了数据类型一致的安全问题。
class Point{
private Object x;
private Object y;
public Point() {
}
public Point(Object x, Object y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
public Object getX() {
return x;
}
public void setX(Object x) {
this.x = x;
}
public Object getY() {
return y;
}
public void setY(Object y) {
this.y = y;
}
}
解决数据类型一致性的安全问题。使用泛型。
泛型的格式:
package com.am.demo02;
/**
* @program: java高级-泛型
* @description:
* @author: 阿木
* @create: 2021-12-20 14:22
**/
public class Test02{
public static void main(String[] args) {
Point<Integer> p1=new Point<>(15,25);
Point<Double> p2=new Point<>(15.5,25.5);
Point<String> p3=new Point<>("东经150度","北纬300度");
Point p4=new Point();//如果没有为泛型设置类型,则默认为Object
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}
//T:习惯用T表示泛型表示。Type
class Point<T>{
private T x;
private T y;
public Point() {
}
public Point(T x, T y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
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;
}
}
通配符
package com.am.demo03;
/**
* @program: java高级-泛型
* @description:
* @author: 阿木
* @create: 2021-12-20 14:48
**/
public class Test03 {
public static void main(String[] args) {
Info<Integer> i=new Info<>();
i.setVar(15);
fun(i);
Info<Double> j=new Info<>();
j.setVar(15.5);
fun(j); //泛型的引用类型传递要求类型匹配而且泛型也要匹配。
//思考: 泛型能否让他传递任意类型? 可以不写 或者使用通配符。
}
public static void fun(Info<?> a){
a.show();
}
}
class Info<T> {
private T var;//成员变量
public void setVar(T var) {
this.var = var;
}
public void show() {
System.out.println("var=======" + var);
}
}
受限泛型
格式:
package com.am.demo04;
import java.util.Collections;
/**
* @program: java高级-泛型
* @description:
* @author: 阿木
* @create: 2021-12-20 15:01
**/
public class Test04 {
public static void main(String[] args) {
Info<Integer> a=new Info<>(25);//创建一个泛型为Integer的info对象
fun1(a);
Info<Number> b=new Info<>(25);
fun1(b);
Info<Double> f=new Info<>(25.5);
fun1(f);
//=======================================================
Info<String> c=new Info<>("hello");
fun2(c);
Info<Object> o=new Info<>(true);
fun2(o);
}
//设置参数的泛型上限。
public static void fun1(Info<? extends Number> a){
a.show();
}
//设置了泛型的下限。必须为String或String的父类
public static void fun2(Info<? super String> b){
b.show();
}
}
class Info<T> {
private T var;
public Info(T var) {
this.var = var;
}
public void show() {
System.out.println("var======" + var);
}
}