当前位置:网站首页>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);
}
}
边栏推荐
- NETCORE combined with cap event bus to realize distributed transaction - message (2)
- xshell 7 官网免费下载
- New关键字、引用&与指针的学习记录
- 分布式并发重复提交问题
- [LDA] rough version notes of EM variational reasoning [to be improved
- Seaborn Brief
- 学习是一件逆人性的事情(成为高手的内功心法)
- Scala download and idea installation of scala plug-ins (nanny level tutorial is super detailed)
- vim的安装以及常用命令
- Idea pull branch code
猜你喜欢
[LDA] LDA theme model notes - mainly Dirichlet
Use of boost:: bind() in ROS
Pta: self test -2 prime pair conjecture (20 points)
[LDA] basic knowledge notes - mainly AE and VAE
Dart typedef的理解
C main函数
Multi thread knowledge induction
[jvm learning] types of GC and allocation process of objects on JVM heap
odom坐标系的理解
C main function
随机推荐
[SPARK][CORE] 面试问题之谈一谈Push-based shuffle
IMU的学习记录
ES6新特性
odom坐标系的理解
NETCORE combined with cap event bus to realize distributed transaction -- Introduction (1)
增加mysql的最大连接数
安装rhel 7/8 (红帽)虚拟机(转载)
Solve log4j2 vulnerability and be attacked by mining and zombie process viruses
Tcp/ip three handshakes and four waves (interview questions)
关于互联网大厂裁员
SQL cross database injection
Is it safe to open an account for flush mobile stock trading
Shardingsphere practice (6) - elastic scaling
TC menu split
Increase the maximum number of MySQL connections
Autofac Beginner (1)
[writeup]buu SQL course1[entry level]
Apprendre est une chose contre la nature humaine
安装PS软件时提示程序无法访问关键文件/目录,错误代码:41的解决方法
Kinect2.0+ORBSLAM2_with_pointcloud_map