当前位置:网站首页>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 .
边栏推荐
- 【1】 Introduction to redis
- How much does small program development cost? Analysis of two development methods!
- Svn incoming content cannot be updated, and submission error: svn: e155015: aborting commit: XXX remains in conflict
- Distributed lock redis implementation
- What are the advantages of small program development system? Why choose it?
- 深度学习(增量学习)——ICCV2022:Contrastive Continual Learning
- 神经网络实现鸢尾花分类
- 小程序开发系统有哪些优点?为什么要选择它?
- Briefly understand MVC and three-tier architecture
- 速查表之各种编程语言小数|时间|base64等操作
猜你喜欢

Distributed cluster architecture scenario optimization solution: distributed ID solution

2: Why read write separation

小程序开发系统有哪些优点?为什么要选择它?

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

深度学习——MetaFormer Is Actually What You Need for Vision

Deep learning (self supervision: simpl) -- a simple framework for contractual learning of visual representations

将项目部署到GPU上,并且运行

word2vec和bert的基本使用方法

《AdaFace: Quality Adaptive Margin for Face Recognition》用于人脸识别的图像质量自适应边缘损失

强化学习——多智能体强化学习
随机推荐
What should we pay attention to when making template application of wechat applet?
The combination of cultural tourism and digital collections has a significant effect, but how to support users' continuous purchasing power
Bert的使用方法
First meet flask
Flink CDC (MySQL as an example)
【四】redis持久化(RDB与AOF)
tf.keras搭建神经网络功能扩展
UNL-类图
Which is more reliable for small program development?
Use Python to encapsulate a tool class that sends mail regularly
【五】redis主从同步与Redis Sentinel(哨兵)
Construction of redis master-slave architecture
Create a virtual environment using pycharm
微信小程序开发费用制作费用是多少?
3: MySQL master-slave replication setup
Kotlin语言现在怎么不火了?你怎么看?
【六】redis缓存策略
Idempotent component
搭建集群之后崩溃的解决办法
Various programming languages decimal | time | Base64 and other operations of the quick look-up table