当前位置:网站首页>Use and understanding of generics
Use and understanding of generics
2022-06-12 15:18:00 【A_ M amu】
1. What makes generics ?
2. Why use generics ?
3. How to use generics 【 class , Interface , On the way 】
4. Limitations of generics .
What makes generics ?
1. Generic : Class is not defined as an attribute in the class , Method [ Return value , Parameters ] Set data type . When creating the object of this class, specify the corresponding data type .
Why use generics ?
Example : Define a point class , attribute :x Coordinates and y coordinate .
requirement : x Coordinates and y The value of the coordinates .
(1) x Coordinates and y The values of the coordinates are all plastic .
(2)x Coordinates and y The values of coordinates are decimal .
(3) x Coordinates and y The values of coordinates are strings .
reflection : x and y Type of attribute .Object. because Object Is the parent of all classes , Because of polymorphism .
package com.am.demo01;
/**
* @program: java senior - Generic
* @description:
* @author: Amur
* @create: 2021-12-20 14:22
**/
public class Test01 {
public static void main(String[] args) {
Point p1=new Point(15,25);// The values are all integers
Point p2=new Point(15.5,25.5);// Values are decimal
Point p3=new Point(" East longitude 150 degree "," North latitude 30 degree ");// Values are strings
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}
// reflection : I can create one Point object , When the object is assigned x Coordinates are integers ,y The coordinates are string . Will this program report an error .【 Can't 】
// Security issues that break the consistency of data types .
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;
}
}Solve the security problem of data type consistency . Use generics .
The format of generics :
public Class name <T,E....>{ //T,E Are generic flags .
public T Property name ;
public T getXXX(){}
public void setXXX(T t){}
}
package com.am.demo02;
/**
* @program: java senior - Generic
* @description:
* @author: Amur
* @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<>(" East longitude 150 degree "," North latitude 300 degree ");
Point p4=new Point();// If no type is set for generics , The default is Object
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}
//T: Used to T Represents a generic representation .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;
}
}
wildcard
In development == Object reference passing == Is the most common , But if in the operation of a generic class , When reference passing == Generic types must match == To deliver , Otherwise, it cannot be transmitted .
package com.am.demo03;
/**
* @program: java senior - Generic
* @description:
* @author: Amur
* @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); // Reference type passing of generics requires type matching, and generics also need to match .
// reflection : Can generics let him pass arbitrary types ? Don't write Or use wildcards .
}
public static void fun(Info<?> a){
a.show();
}
}
class Info<T> {
private T var;// Member variables
public void setVar(T var) {
this.var = var;
}
public void show() {
System.out.println("var=======" + var);
}
}
Restricted generics
stay == reference == in , In generic operations, you can also set the upper and lower range limits of a generic object . The upper limit of the range is used extends Keyword declaration , Indicates that the parameterized type may be the specified type or a subclass of this type , The lower range limit uses super Make a statement , Indicates that the parameterized type may be the specified type or the parent type of this type .
Format :
[ Set the upper limit ]
Declare objects : Class name <? extends class > Object name ;
Defining classes : [ Access right ] Class name < Generic identity extends class >{}[ Set the lower limit ]
Declare objects : Class name <? super class > Object name ;
Defining classes : [ Access right ] Class name < Generic identity super class >{}
package com.am.demo04;
import java.util.Collections;
/**
* @program: java senior - Generic
* @description:
* @author: Amur
* @create: 2021-12-20 15:01
**/
public class Test04 {
public static void main(String[] args) {
Info<Integer> a=new Info<>(25);// Create a generic as Integer Of info object
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);
}
// Set the Generic upper limit of the parameter .
public static void fun1(Info<? extends Number> a){
a.show();
}
// Set the lower limit of generics . It has to be for String or String Parent class of
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);
}
}
边栏推荐
猜你喜欢

ROS beginners write the server that the little turtle rotates a certain angle at a certain speed

Two ways of array simulating queue

Pointer related concepts

Seaborn Brief

Multi thread knowledge induction

TCP与UDP的区别,以及TCP的三次握手和TCP的四次挥手

How to set public IP access on the H3C gr5200 router

TC menu split
![[writeup]buu SQL course1[entry level]](/img/eb/1b2541b04ca231cb07f1f3706f51c7.png)
[writeup]buu SQL course1[entry level]

TCP/IP 三次握手四次挥手(面试题)
随机推荐
Module yaml error: Unexpected key in data: static_ context [line 9 col 3]
Jetpack architecture component learning (3) -- activity results API usage
IGMP报文(TCP/IP详解卷1/卷2)
Browser fingerprint interpretation
sql server 2008 的导入导出步骤
#include使用“文件名“和<文件名>引入头文件的区别及简述
FIRSTVT和LASTVT白话版
ssm中的文件上传和下载
Function related matters
Idea pull branch code
Loadbalancer load balancer
Simple crawler framework: parsing 51job page position information
Learning is an inhumane thing (becoming an expert's internal mind skill)
[LDA] basic knowledge notes - mainly AE and VAE
Scala下载及IDEA安装Scala插件(保姆级教程超详细)
Change according to the situation, the road to promotion in the second half of 2022
Xshell 7 official website free download
Pta: self TEST-1 print Hourglass (20 points)
[untitled]
ROS中tf学习笔记