当前位置:网站首页>Knowledge point 21 generic
Knowledge point 21 generic
2022-07-28 06:10:00 【Alan and fish】
Knowledge point 21- Generic
1. Generic overview
When we learned about collections earlier , We all know that any object can be stored in a collection , Just store the objects together , Then they will all be promoted to Object type . When we are taking out every object , And carry out the corresponding operation , You have to use type conversion .
Look at the following code :
public class GenericDemo {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add("abc");
coll.add("itcast");
coll.add(5);// Because the set doesn't have any restrictions , Any type can be stored in it
Iterator it = coll.iterator();
while(it.hasNext()){
// You need to print the length of each string , It's about turning the iterated object into String type
String str = (String) it.next();
System.out.println(str.length());
}
}
}
Something went wrong while the program was running java.lang.ClassCastException. Why do type conversion exceptions occur ? Let's analyze : Because any type of element in the collection can be stored . Causes a strong rotation at take-out to cause runtime ClassCastException. How to solve this problem ? Collection Although it can store a variety of objects , But it's usually Collection Store only objects of the same type . For example, they store string objects . So in JDK5 after , Added Generic (Generic) grammar , Let you design API You can specify that classes or methods support generics , So we use API It also becomes more concise , And get the syntax check at compile time .
- Generic : You can use an unknown type in a class or method in advance .
tips: Generally when creating objects , Determine the specific type of unknown type . When no generics are specified , The default type is Object type .
2. Benefits of using generics
The previous section just explained the introduction of generics , So what are the benefits of generics ?
- Will run the ClassCastException, The transition to compile time becomes Compile failure .
- Avoid the trouble of type strong turn .
Let's experience it with the following code :
public class GenericDemo2 {
public static void main(String[] args) {
Collection<String> list = new ArrayList<String>();
list.add("abc");
list.add("itcast");
// list.add(5);// When the set specifies the type , If the storage type is inconsistent, an error will be reported
// The collection has specified the type of elements to store , So when using iterators , Iterators also know the specific traversal element type
Iterator<String> it = list.iterator();
while(it.hasNext()){
String str = it.next();
// When using Iterator<String> After controlling element type , There's no need for a strong turn . The element obtained is directly String type
System.out.println(str.length());
}
}
}
tips: Generics are part of data types , We think of class names and generic merges as data types .
3. Definition and use of generics
We use generics a lot in collections , Here's a complete study of generics .
Generic , Used to flexibly apply data types to different classes 、 Method 、 In the interface . Passing data types as parameters .
1. Define and use classes with generics
Define format :
Modifier class Class name < Variables representing generics > { }
for example ,API Medium ArrayList aggregate :
class ArrayList<E>{
public boolean add(E e){
}
public E get(int index){
}
....
}
Use generics : When to determine generics .
Determine generics when creating objects
for example ,ArrayList<String> list = new ArrayList<String>();
here , Variable E The value is String type , So our type can be understood as :
class ArrayList<String>{
public boolean add(String e){
}
public String get(int index){
}
...
}
Another example is ,ArrayList<Integer> list = new ArrayList<Integer>();
here , Variable E The value is Integer type , So our type can be understood as :
class ArrayList<Integer> {
public boolean add(Integer e) {
}
public Integer get(int index) {
}
...
}
Examples of custom generic classes
public class MyGenericClass<MVP> {
// No, MVP type , It stands for An unknown data type What kind of future transmission is
private MVP mvp;
public void setMVP(MVP mvp) {
this.mvp = mvp;
}
public MVP getMVP() {
return mvp;
}
}
Use :
public class GenericClassDemo {
public static void main(String[] args) {
// Create a generic as String Class
MyGenericClass<String> my = new MyGenericClass<String>();
// call setMVP
my.setMVP(" Big Hu Zi Deng ");
// call getMVP
String mvp = my.getMVP();
System.out.println(mvp);
// Create a generic as Integer Class
MyGenericClass<Integer> my2 = new MyGenericClass<Integer>();
my2.setMVP(123);
Integer mvp2 = my2.getMVP();
}
}
2. Methods with generics
Define format :
Modifier < Variables representing generics > return type Method name ( Parameters ){ }
for example ,
public class MyGenericMethod {
public <MVP> void show(MVP mvp) {
System.out.println(mvp.getClass());
}
public <MVP> MVP show2(MVP mvp) {
return mvp;
}
}
Use format : When calling a method , Determine the type of generics
public class GenericMethodDemo {
public static void main(String[] args) {
// Create objects
MyGenericMethod mm = new MyGenericMethod();
// Show me the tips
mm.show("aaa");
mm.show(123);
mm.show(12.45);
}
}
3. Interfaces with generics
Define format :
Modifier interface The interface name < Variables representing generics > { }
for example ,
public interface MyGenericInterface<E>{
public abstract void add(E e);
public abstract E getE();
}
Use format :
1、 Determine the type of generics when defining classes
for example
public class MyImp1 implements MyGenericInterface<String> {
@Override
public void add(String e) {
// Omit ...
}
@Override
public String getE() {
return null;
}
}
here , Generic E The value is String type .
2、 Always uncertain about the type of generics , Until the object is created , Determine the type of generics
for example
public class MyImp2<E> implements MyGenericInterface<E> {
@Override
public void add(E e) {
// Omit ...
}
@Override
public E getE() {
return null;
}
}
Determine generics :
/* * Use */
public class GenericInterface {
public static void main(String[] args) {
MyImp2<String> my = new MyImp2<String>();
my.add("aa");
}
}
4. Generic wildcard
When using generic classes or interfaces , In the data transferred , Generic types are uncertain , You can use wildcards <?> Express . But once you use a generic wildcard , Only use Object Common methods in class , The element's own method in the collection cannot be used .
1. Wildcards are basically used
Generic wildcards : Don't know what type to use to receive , You can use ?,? Represents an unknown wildcard .
Only data can be accepted at this time , Data cannot be stored in this collection .
For example, if you understand how to use it :
public static void main(String[] args) {
Collection<Intger> list1 = new ArrayList<Integer>();
getElement(list1);
Collection<String> list2 = new ArrayList<String>();
getElement(list2);
}
public static void getElement(Collection<?> coll){
}
//? Delegate can receive any type of
tips: Generics don't have inheritance Collection list = new ArrayList(); This is wrong .
2. Advanced use of wildcards ---- Restricted generics
When I set generics before , It can be set at will , As long as it's a class, you can set . But in JAVA You can specify a generic ceiling and Lower limit .
The upper limit of generics :
- Format :
Type the name <? extends class > Object name - significance :
Only the type and its subclasses can be accepted
The lower bound of generics :
- Format :
Type the name <? super class > Object name - significance :
You can only receive this type and its parent type
such as : Now known Object class ,String class ,Number class ,Integer class , among Number yes Integer Parent class of
public static void main(String[] args) {
Collection<Integer> list1 = new ArrayList<Integer>();
Collection<String> list2 = new ArrayList<String>();
Collection<Number> list3 = new ArrayList<Number>();
Collection<Object> list4 = new ArrayList<Object>();
getElement(list1);
getElement(list2);// Report errors
getElement(list3);
getElement(list4);// Report errors
getElement2(list1);// Report errors
getElement2(list2);// Report errors
getElement2(list3);
getElement2(list4);
}
// The upper limit of generics : Generics at this point ?, Must be Number Type or Number Subclass of type
public static void getElement1(Collection<? extends Number> coll){
}
// The lower bound of generics : Generics at this point ?, Must be Number Type or Number The parent of type
public static void getElement2(Collection<? super Number> coll){
}
5. Application of generics
Based on SSM Or is it Springboot In the project , In fact, more deletion and modification can be checked through one Baseservice Class unified call .
When I use it here tx.mybatis, This framework is mybatis Development of , He inherited the role of BaseMapper, ExampleMapper, RowBoundsMapper, Marker Four interfaces , The inside covers all the more deletion and modification methods .
1. Create a BaseService

This service As shown in the figure , Here is just an example , Create a query for all public methods .
2. Create a Service Inherit this class
Because inheritance has all the methods of the parent class , We can start with BaseService Create our most commonly used method , Then inherit this baseservice You can call it directly , province A lot of code .
3. test
my DemoService There is no other way , You can query , The test results are as follows .
When I was working on a project, I saw that other people's projects can use the general deletion and modification check in this way , So I learned this generic knowledge systematically , Most of this document comes from the class of dark horse programmers , Just for learning , Not for commercial use , If there is infringement , Please contact me to delete .
边栏推荐
- No module named yum
- Invalid packaging for parent POM x, must be “pom“ but is “jar“ @
- NLP中基于Bert的数据预处理
- Distributed cluster architecture scenario optimization solution: distributed ID solution
- What about the app store on wechat?
- 字节Android岗4轮面试,收到 50k*18 Offer,裁员风口下成功破局
- How much does it cost to make a small program mall? What are the general expenses?
- 分布式集群架构场景化解决方案:集群时钟同步问题
- KubeSphere安装版本问题
- Distributed cluster architecture scenario optimization solution: session sharing problem
猜你喜欢

How much is wechat applet development cost and production cost?

字节Android岗4轮面试,收到 50k*18 Offer,裁员风口下成功破局

How to do wechat group purchase applet? How much does it usually cost?

Pytorch deep learning single card training and multi card training

分布式集群架构场景优化解决方案:Session共享问题

Manually create a simple RPC (< - < -)

深度学习——Patches Are All You Need

Centos7 installing MySQL

Construction of redis master-slave architecture

Micro service architecture cognition and service governance Eureka
随机推荐
Uview upload component upload upload auto upload mode image compression
深度学习(增量学习)——ICCV2022:Contrastive Continual Learning
What should we pay attention to when making template application of wechat applet?
How to do wechat group purchase applet? How much does it usually cost?
How to use Bert
raise RuntimeError(‘DataLoader worker (pid(s) {}) exited unexpectedly‘.format(pids_str))RuntimeErro
2: Why read write separation
深度学习——MetaFormer Is Actually What You Need for Vision
【五】redis主从同步与Redis Sentinel(哨兵)
【6】 Redis cache policy
Two methods of covering duplicate records in tables in MySQL
强化学习——Proximal Policy Optimization Algorithms
《AdaFace: Quality Adaptive Margin for Face Recognition》用于人脸识别的图像质量自适应边缘损失
Idempotent component
卷积神经网络
Manually create a simple RPC (< - < -)
【六】redis缓存策略
The project does not report an error, operates normally, and cannot request services
深度学习(自监督:MoCo V3):An Empirical Study of Training Self-Supervised Vision Transformers
Distributed cluster architecture scenario optimization solution: distributed ID solution