当前位置:网站首页>day15_ generic paradigm
day15_ generic paradigm
2022-07-29 06:33:00 【Fat uncle talking about Java】
Generic
Learning goals
1. Understand the role of generics
2. Proficiency in custom generics
3. Master the advanced use of generics
4. Generic applications
One 、 Generic introduction
from JDK5 in the future ,Java Introduced “ Parameterized types (Parameterized type)” The concept of .
Generic type , It is allowed to define the class 、 The interface represents the type of a property in a class or the return value and parameter type of a method through an identifier . This type parameter will be determined when used **( for example , Inherit or implement this interface , Declare variables with this type 、 When you create an object, you pass in the real Type parameters of the , Also known as type arguments )**
Generic starter case :
/** Generic starter case : */
// use T Represents a data type
public class Person<T> {
private int id;
private String name;
// Definition T Type attribute ,T The type is determined when used
private T t;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public static void main(String[] args) {
// Create objects , Specifying generics T The type of
Person<Integer> person = new Person<Integer>();
// Set properties
person.setId(1);
person.setName(" Xiaohong ");
person.setT(12);
// Value
System.out.println(person.getId());
System.out.println(person.getName());
System.out.println(person.getT());
// Create objects , Specifying generics T The type of
Person<String> person2 = new Person<String>();
// Set properties
person2.setId(2);
person2.setName(" petty thief ");
person2.setT("abc");
// Value
System.out.println(person2.getId());
System.out.println(person2.getName());
System.out.println(person2.getT());
}
}
Two 、 Custom generic structures
2.1 Custom generic classes
Custom generic class syntax

Example 1: Custom generic classes
/** 1. Define generics for classes */
// 1. Define generics
public class User<T,E> {
private int id;
private String name;
private String pwd;
//2. attribute : Use generics
private T t;
private E e;
//3. Method : Use generics
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public E getE() {
return e;
}
public void setE(E e) {
this.e = e;
}
//4. Constructors : Use generics
public User(int id, String name, String pwd, T t, E e) {
this.id = id;
this.name = name;
this.pwd = pwd;
this.t = t;
this.e = e;
}
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + ", t=" + t + ", e=" + e + "]";
}
public static void main(String[] args) {
//1. Use generics and test
User<String,Integer> user = new User<String, Integer>(1, " Little black ", "123456", " Generic 1", 22);
//2. Call the property
Integer i = user.e;
String str = user.t;
System.out.println(i);
System.out.println(str);
//3. Method
user.setE(1);
user.setT(" String type ");
Integer i2 = user.getE();
String str2 = user.getT();
System.out.println(user);
}
}
2.2 Custom generic methods
Method , It can also be generalized , Whether the class defined in it is a generic class or not . Generic parameters can be defined in generic methods , here , The type of parameter is the type of incoming data .
Generic method syntax

Example 1: Generic methods
public class MethodType {
public static <T> void method1(T t) {
System.out.println(t);
}
public static <T> T method2(T t) {
return t;
}
public static void main(String[] args) {
MethodType.method1(" Little black ");
Date date = MethodType.method2(new Date());
System.out.println(date);
}
}
2.3 Precautions for using generics
- Generic if not specified , Will be erased , The types corresponding to generics are in accordance with Object Handle , But it's not equivalent to Object. Experience : Generics should be used all the way . If not , Don't use it all the way .
- jdk7, Simplified operation of generics :ArrayList flist = new ArrayList<>();
- Basic data types cannot be used in the specification of generic types , You can use wrapper classes to replace .
- In the class / The generic type declared on the interface , In this class or interface, it represents a certain type , Can be used as a type of non static attribute 、 Parameter types of non static methods 、 The return value type of a non static method . But in static methods Generic types of classes cannot be used in .
- Exception classes cannot be generic
- The parent class has a generic type , Subclasses can choose to keep generics or specify generic types :
- Subclasses do not retain the generics of the parent class : On demand
- There is no type erase
- The specific type
- Subclasses retain the generics of the parent class : Generic subclass
- Keep it all
- Partial reservation
- Subclasses do not retain the generics of the parent class : On demand
Example 1: Precautions for using generics
/** * Precautions for using generics * 1. Generic if not specified , Will be erased , The types corresponding to generics are in accordance with Object Handle , But it's not equivalent to Object. Experience : Generics should be used all the way . If not , Don't use it all the way . * 2.jdk7, Simplified operation of generics : User<String> user = new User<>(); * 3. Basic data types cannot be used in the specification of generic types , You can use wrapper classes to replace . * 4. In the class / The generic type declared on the interface , In this class or interface, it represents a certain type , Can be used as a type of non static attribute 、 Parameter types of non static methods 、 The return value type of a non static method . But in static methods Generic types of classes cannot be used in . * 5. Exception classes cannot be generic */
public class Demo1 {
public static void main(String[] args) {
// Generic does not specify , Will be erased , according to Object Type processing
User user = new User();
user.setT("abc");
System.out.println(user.getT());
// Specify the simplified writing of generics
User<String> user2 = new User<>();
user2.setT("abc");
// Generic types can only be specified as reference types , It can't be the basic type
//User<int> user3 = new User<>(); Report errors
}
}
class User<T>{
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
// Generics declared on classes cannot be used in static methods
// public static T method1(T t){
// return t;
// }
}
Example 2: Note on generics
/** * The parent class has a generic type , Subclasses can choose to keep generics or specify generic types : * 1. Subclasses do not retain the generics of the parent class : On demand * 1. There is no type erase * 2. The specific type * 2. Subclasses retain the generics of the parent class : Generic subclass * 1. Keep it all * 2. Partial reservation */
public class Demo2 {
public static void main(String[] args) {
}
}
class Father<A,B>{
public A a;
public B b;
}
class Son1 extends Father{
}// Subclasses do not retain the parent generic , Equivalent to class Son1 extends Father<Object,Object>
class Son2 extends Father<String,Integer>{
}// Subclasses do not retain the parent generic , But assign generic types to the parent class
class Son3<A,B> extends Father<A,B>{
}// All subclasses retain the generic type of the parent class
class Son4<A> extends Father<A,String>{
}// Subclasses retain some generics of the parent class
2.4 Summary
- Where can generic types be declared ( class 、 Interface 、 Method )
- Considerations for using generics
3、 ... and 、 Advanced applications of generics
3.1 Specifies the Generic upper limit
When declaring generics , Can pass extends Keyword specifies the upper limit of the generic type .
Example 1: Generics can only be B Type or B Subclass of type
/** * Specify the upper limit of the generic */
public class ParameterizedTypeDemo<T extends B> {
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public static void main(String[] args) {
// Generics can only be used as B Type or B Subclass of type
ParameterizedTypeDemo<C> parameterizedTypeDemo = new ParameterizedTypeDemo<>();
// Report errors
//ParameterizedTypeDemo<String> stringParameterizedTypeDemo = new ParameterizedTypeDemo<String>();
// Report errors
//ParameterizedTypeDemo<A> aParameterizedTypeDemo2 = new ParameterizedTypeDemo<A>();
}
}
class A {
}
class B extends A{
}
class C extends B{
}
3.2 Considerations in inheritance
If B yes A A subtype of ( Subclass or sub interface ), and G Is a generic declaration Class or interface ,G<B> Not at all G<A> Subtypes of !
such as :String yes Object Subclasses of , however User<String > Not at all User<Object> Subclasses of ; This is actually a very obvious problem , Both are User type , It's just that generics are different , This is a big factory interview question .
3.3 The use of wildcards
Although I say however User<String > Not at all User<Object> Subclasses of , however User There is indeed a parent class ; This involves ? The use of wildcards , The wildcard syntax is as follows :
- ? Represent wildcard ,User<?> yes User、User、User Parent class of
- Read User<?> The properties of the object , Always safe , Because I don 't care User What is the real type of , It contains all Object.
- write in User<?> Object attribute of cannot be . Because we don't know ? Element type of , We cannot set attribute values ; The only exception is null, It is a member of all types
Example 1: The use of wildcards
package top.psjj.demo1;
/** * The use of generic wildcards * 1. ? Represent wildcard ,User<?> yes User<String>、User<Integer>、User<Object> Parent class of 2. Read User<?> The properties of the object , Always safe , Because I don 't care User What is the real type of , It contains all Object. 3. write in User<?> Object attribute of cannot be . Because we don't know ? Element type of , We cannot set attribute values ; The only exception is null, it Is a member of all types */
public class ParameterizedTypeDemo2{
public static void main(String[] args) {
User<String> user = new User<>();
//user2 yes user Parent class of
User<?> user2 = new User<>();
// Read User<?> The properties of the object , Always safe , Because I don 't care user What is the real type of , It contains all Object.
System.out.println(user2.getT());
//3. write in User<?> Object attribute of cannot be . Because we don't know ? Element type of , We cannot set attribute values ; The only exception is null, it Is a member of all types
// user2.setT(10); // Report errors
user2.setT(null);
}
}
class User<T>{
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
3.4 The upper and lower limits of wildcards
The upper and lower limits of wildcards are specified
- ceiling extends: The type specified when using must inherit a class , Or implement an interface , namely <=
- Lower limit super: The type specified when using cannot be less than the class of the operation , namely >=
Example 1: Specify the upper and lower limits of wildcards
/** * The upper and lower limits of wildcards are specified * 1. ceiling extends: The type specified when using must inherit a class , Or implement an interface , namely <= * 2. Lower limit super: The type specified when using cannot be less than the class of the operation , namely >= */
public class Student<T>{
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public static void main(String[] args) {
// Specify the upper limit generic of wildcard Number
Student<? extends Number> student = new Student();
// The generics are Integer Type of student1 It is a subclass of the above class
Student<Integer> student1 = new Student<>();
// The generics are String Type of student2 and student It doesn't matter.
Student<String> student2 = new Student<>();
// The upward transformation was established
student = student1;
// Upward transformation failed
//student = student2;
// Specify the lower bound generics of wildcards Integer
Student<? super Integer> s1 = new Student();
Student<Number> s2 = new Student<>();
}
}
Be careful : wildcard **?** Is the use of generics , Not a statement , So you can't declare in class , Use on method declarations

Wildcards can only be used on the left side of the object creation

3.5 Summary
- Specify the upper limit of the generic
- The use of wildcards
Four 、 Generic applications
Whether natural sorting or custom sorting, the bottom layer of the interface is to declare generics , As shown below :

4.1 Natural sorting applies generics
Example 1: Sort by user age
/* Natural ordering */
public class User implements Comparable<User> {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(User u) {
if(u==null){
throw new NullPointerException("null Cannot participate in sorting ");
}
return this.age-u.getAge();
}
public static void main(String[] args) {
User[] users = new User[3];
for (int i = 0; i < users.length ; i++) {
users[i] = new User((i+1)," Zhang San "+i,(int)(Math.random()*100));
}
// Array sorting
Arrays.sort(users);
// View the contents of the array
System.out.println(Arrays.toString(users));
}
}
4.2 Custom sorting applies generics
Example 2: Sort by user age
public class User {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public static void main(String[] args) {
User[] users = new User[3];
for (int i = 0; i < users.length ; i++) {
users[i] = new User((i+1)," Zhang San "+i,(int)(Math.random()*100));
}
// Array sorting : Custom sort
Arrays.sort(users,new Comparator<User>(){
@Override
public int compare(User u1, User u2) {
if(u1==null || u2==null){
throw new NullPointerException(" The sorting user cannot be null");
}
return u1.getAge()-u2.getAge();
}
});
// View the contents of the array
System.out.println(Arrays.toString(users));
}
}
5、 ... and 、 summary
- Declaration and use of generics
- The upper limit of generics
- Generic wildcards
- Generic applications
- Generics can avoid type conversion exceptions
边栏推荐
- 网站服务器80,443端口一直被恶意攻击怎么办?
- Plugin location in mavan
- Leetcode scribble notes 763. Divide the letter range (medium)
- Maya aces workflow configuration (Arnold and redshift map configuration specification - restore the correct effect of the map under the SP aces process) PS restore the rendered map under the aces proc
- 用神经网络实现手写数字识别
- day15_泛型
- day09_ Static & Final & code block & abstract class & Interface & internal class
- 高级套接口编程(选项和控制信息)
- 什么是撞库及撞库攻击的基本原理
- Leetcode 83. delete duplicate elements in the sorting linked list
猜你喜欢

官方教程 Redshift 04 渲染参数

Vivado IP核之浮点数加减法 Floating-point

虹科Automation softPLC | 虹科KPA MoDK运行环境与搭建步骤(2)——MoDK运行环境搭建

Vivado IP核之定点数转为浮点数Floating-point

Vivado IP核之浮点数开方 Floating-point

day09_ Static & Final & code block & abstract class & Interface & internal class

虹科分享 | 带您全面认识“CAN总线错误”(一)——CAN总线错误与错误帧

day13_多线程下

虹科 | 使用JESD204串行接口高速桥接模拟和数字世界
![[leetcode brush questions] array 3 - divide and conquer](/img/76/bc3d9ba0b84578e17bf30195bda5d1.png)
[leetcode brush questions] array 3 - divide and conquer
随机推荐
官方教程 Redshift 05 AOVs
虹科分享 | 如何测试与验证复杂的FPGA设计(1)——面向实体或块的仿真
Redshift 2.6.41 for maya2018 水印去除
TCP套接口通信实验
进程与线程
盘点 | 全球关键信息基础设施网络安全大事件
Leetcode scribble notes 763. Divide the letter range (medium)
[interview questions] the latest software test interview questions in 2022 (400) [with answers] continue to update
八、 网络安全
PDO的使用
Access、Hybrid和Trunk三种模式的理解
Official tutorial redshift 04 rendering parameters
Arrays&Object&System&Math&Random&包装类
六、 网络互联与互联网
网络安全学习(一)
软件测试的优势有哪些?看看你了解多少.....
7110 digital trend 2 solution
超低成本DDoS攻击来袭,看WAF如何绝地防护
四、 局域网和城域网
c语言问题