当前位置:网站首页>What is generics- Introduction to generics
What is generics- Introduction to generics
2022-07-02 16:56:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
Catalog
1、 What is generics ?
Generics are actually passing types as parameters , Generics allow programmers to write code using types that are specified later , When instantiating the class, pass the desired type as a parameter , To indicate these types .
Why introduce generics ?
for example : Implement a sequence table by yourself
public class MyArrayList {
public int[] elem;
public int usedSize;
public MyArrayList() {
this.elem = new int[10];
}
// add Method
public void add(int val) {
// Capacity expansion will not be considered for the time being , This is just to talk about generics
elem[usedSize++] = val;
}
// get Method
public int get(int pos) {
return elem[pos];
}
}You can see here , When using the custom order table above , We Only add int type The elements of , We know java Sequence table in set , You can add Any kind of The data of , How to achieve it ? Here we try to make int Type changed to Object type , This ensures that any type can be passed in .
public class MyArrayList {
public Object[] elem;
public int usedSize;
public MyArrayList() {
this.elem = new Object[10];
}
// add Method
public void add(Object val) {
// Capacity expansion will not be considered for the time being , This is just to talk about generics
elem[usedSize++] = val;
}
// get Method
public Object get(int pos) {
return elem[pos];
}
}main Method to add data to an object , You can add any type of data . however , When data needs to be retrieved , Because the return is Object type , Strong conversion is required to receive... With the corresponding type , Very trouble .
public static void main(String[] args) {
MyArrayList myArrayList = new MyArrayList();
myArrayList.add(1);
myArrayList.add("hello");
int array1 = (int)myArrayList.get(0);
String array2 = (String)myArrayList.get(1);
}So here's the question , Do you have to turn around every time to receive it , Can we not make a strong turn ? At this time, we think of creating an instance object , You can pass the desired type as a parameter , Let this object store all the data of the incoming type , So when you take it out , You can make it clear that all data in the object is of this type , There's no need for forced rotation . This introduces generics .
public class MyArrayList<E> {
// When writing a program , Do not specify a specific type , While using <E> there E For the time being
// The specific type is passed in when instantiating the object
public E[] elem;
public int usedSize;
public MyArrayList() {
// The writing here is not particularly accurate , The reflection mechanism should be used , Let's start here
this.elem = (E[])new Object[10];
}
// add Method
public void add(E val) {
// Capacity expansion will not be considered for the time being , This is just to talk about generics
elem[usedSize++] = val;
}
// get Method
public E get(int pos) {
return elem[pos];
}
}public static void main(String[] args) {
MyArrayList<Integer> myArrayList1 = new MyArrayList<>();
myArrayList1.add(1);
myArrayList1.add(3);
// myArrayList1.add("world");// There will be an error , Because the incoming data is not of the specified type , So generics also have the function of automatically checking types
int I1 = myArrayList1.get(0);
MyArrayList<String> myArrayList2 = new MyArrayList<>();
myArrayList2.add("hello");
myArrayList2.add("world");
String s1 = myArrayList2.get(0);
}This ensures that any type of data can be passed in , At the same time, you don't need to turn when you take it out ! The significance of generics : 1、 Automatically check the type 2、 Automatically cast types
So here MyArrayList What is the type of the corresponding object ? yes MyArrayList< Integer > Like that ?
You can see here , The types of objects created by the instance are MyArrayList, and <> The content in does not participate in the composition of generic types , that <> Where are the types inside ? It's time to understand how generics work .
2、 How generics are compiled
An important difference between arrays and generics is how they force type checking . say concretely , Arrays store and check type information at run time . however , Generics check for type errors at compile time , And there is no type information at run time .
Compilation mechanism of generics : Erasure mechanism
At compile time , take MyArrayList Medium E It's rubbed Object type .
stay main The method has been rubbed into MyArrayList type .
Reference resources : stay java Create a generic array
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/147849.html Link to the original text :https://javaforall.cn
边栏推荐
- Hard core! One configuration center for 8 classes!
- System Verilog实现优先级仲裁器
- Take you ten days to easily complete the go micro service series (I)
- 小鹏P7雨天出事故安全气囊没有弹出 官方回应:撞击力度未达到弹出要求
- john爆破出现Using default input encoding: UTF-8 Loaded 1 password hash (bcrypt [Blowfish 32/64 X3])
- Notice on holding a salon for young editors of scientific and Technological Journals -- the abilities and promotion strategies that young editors should have in the new era
- PCL 点云镜像变换
- ⌈ 2022 ⌋ how to use webp gracefully in projects
- Routing mode: hash and history mode
- lsf基础命令
猜你喜欢

sql解决连续登录问题变形-节假日过滤

Digital IC hand tearing code -- voting device

基于多元时间序列对高考预测分析案例

Just a coincidence? The mysterious technology of apple ios16 is even consistent with the products of Chinese enterprises five years ago!

La boîte de connexion du hub de l'unit é devient trop étroite pour se connecter

What is normal distribution? What is the 28 law?
![[error record] the connection of the flutter device shows loading (disconnect | delete the shuttle/bin/cache/lockfile file)](/img/3f/79dcfcd88d779a5d493b4b539bd448.jpg)
[error record] the connection of the flutter device shows loading (disconnect | delete the shuttle/bin/cache/lockfile file)

go-zero微服务实战系列(八、如何处理每秒上万次的下单请求)

渗透工具-内网权限维持-Cobalt strike

Where can I open computer administrator permissions
随机推荐
Interview summary of large factories
Global and Chinese market of oil analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
john爆破出现Using default input encoding: UTF-8 Loaded 1 password hash (bcrypt [Blowfish 32/64 X3])
Global and Chinese market of discharge machines 2022-2028: Research Report on technology, participants, trends, market size and share
Student course selection system (curriculum design of Shandong Agricultural University)
La boîte de connexion du hub de l'unit é devient trop étroite pour se connecter
SSM integration exception handler and project exception handling scheme
P6774 [NOI2020] 时代的眼泪(分块)
lsf基础命令
深度学习图像数据自动标注[通俗易懂]
你想要的宏基因组-微生物组知识全在这(2022.7)
July 1st gift: Yi Jingjie's "hundred day battle" ended perfectly, and the database of Guiyang bank was sealed in advance
Written by unity Jason
[cloud native] briefly talk about the understanding of flume, a massive data collection component
Résumé de l'entrevue de Dachang Daquan
uboot的作用和功能
C语言中sprintf()函数的用法
Leetcode1380: lucky numbers in matrix
PCL 点云镜像变换
Privacy computing technology innovation and industry practice seminar: Learning