当前位置:网站首页>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初学者编写小乌龟以一定速度旋转一定角度的server

Servlet连接数据库实现用户登录功能

Pointer related concepts

Servlet知识详解(2)

Change according to the situation, the road to promotion in the second half of 2022

Left aligned, right aligned, random number, goto, compare output bool

Microservice fault tolerance
![[jvm learning] virtual machine stack](/img/64/4942c572f1ae4e4c6e2a6b657660e3.jpg)
[jvm learning] virtual machine stack

Kinect2.0+ORBSLAM2_with_pointcloud_map

New关键字、引用&与指针的学习记录
随机推荐
Error 1105: message:\“raft entry is too large
Array related content
Learning is an inhumane thing (becoming an expert's internal mind skill)
Tcp/ip three handshakes and four waves (interview questions)
粒子滤波学习记录
【无标题】
Deepin20.6 rtx3080 installing graphics card drivers 510.60.02, cuda11.6, pytorch1.11
应势而变,2022年下半场的升级之路
3D reconstruction system | L3 dual view motion recovery structure (SFM binocular SFM)
Notes on ARM 64 instructions
虚拟机中用户和root忘记密码解决办法
频繁项集产生强关联规则的过程
Deepin20.6 RTX3080 安装显卡驱动510.60.02、CUDA11.6、PyTorch1.11
Rust tip - running the tensorrt model through FFI programming
Error 1105: message:\“raft entry is too large
[wp][beginner level] attack and defense world game
ROS初学者编写小乌龟以一定速度旋转一定角度的server
Solution to the new database prompt on the pagoda panel that the database name cannot be greater than 16 bits
PTA:自测-2 素数对猜想 (20分)
UDP总结(TCP/IP详解卷1/2)