当前位置:网站首页>What is a generic? Why use generics? How do I use generics? What about packaging?
What is a generic? Why use generics? How do I use generics? What about packaging?
2022-06-11 16:13:00 【Java ape~】
Catalog
️ The basic type corresponds to the packaging class
Automatic packing and unpacking
Why generics
Let's first implement a simple version with an array MyArrar, Inside the store int Element of type
public class MyArray {
int[] array;
int size; // Number of valid elements in the array
public MyArray(int initCapacity){
if(initCapacity <= 0){
initCapacity = 10;
}
array = new int[initCapacity];
}
// Tail insertion
public void add(int e){
if(size >= array.length){
System.out.println("MyArray It's full ");
return;
}
array[size] = e;
size++;
}
// obtain index Elements in position
public int get(int index){
if(index<0 || index>=size){
throw new ArrayIndexOutOfBoundsException(" Array subscript out of bounds ");
}
return array[index];
}
public static void main(String[] args) {
MyArray myArray = new MyArray(5);
myArray.add(1);
myArray.add(2);
}
}But we Don't want to In the MyArray in add to int type The elements of , What would ?
Creating a class ? It does not reflect the reusability of the code , too trouble
Use Object type Come on receive data ? Sure , Let's create MyArray, Creating a Student And a class Person class , And add some data , See what problems will be revealed when using ?
class Person{
int age;
String name;
}
class Student{
String name;
int age;
}
public class MyArray {
Object[] array;
int size;
public MyArray(int initCapacity){
if(initCapacity <= 0){
initCapacity = 10;
}
array = new Object[initCapacity];
}
public void add(Object e){
if(size >= array.length){
System.out.println("MyArray It's full ");
return;
}
array[size] = e;
size++;
}
public Object get(int index){
if(index<0 || index>=size){
throw new ArrayIndexOutOfBoundsException(" Array subscript out of bounds ");
}
return array[index];
}
public static void main(String[] args) {
MyArray myArray = new MyArray(10);
myArray.add(new Person());
myArray.add(new Person());
myArray.add(new Student());
myArray.add(new Student());
}
}
I want to get one Person object

If you find out, you will report an error , Think about why ?
because MyArray Deposit is Object,Object Is the parent of all classes , So here There is a downward transformation , The downward transformation is unsafe Of , So we have to turn around

At this time, the problem is solved
But there is another problem at this time :

Observe , It was found that Person type , Why Student Type reception , The compiler does not report errors ?
We can run it to see how it turns out :

ClassCastException by Type conversion exception , It's a kind of Runtime error , So in No errors will be reported during compilation , Will complete the compilation , But an error will be reported at runtime
Why this kind of mistake ?
because MyArray We usually don't know what kind of things are stored in it , So when receiving , Unable to select the correct type to receive , So it will lead to this kind of error
So for the above question , Use Object type To receive can be achieved , but Not an option , Because there will be Move down , And the class Type conversion error , It makes us write very trouble
This is the time , Generics appear , Use Generic Can solve the above problems very well
️ Know generics
Generics refer to type parameterization , That is, set the type to a specific format parameter when writing code , This parameter can specify different types to control the type of formal parameter specific restrictions
️️ Use generics to modify the above code to realize the usage of generics
public class MyArray<T> {
T[] array;
int size;
public MyArray(int initCapacity){
if(initCapacity <= 0){
initCapacity = 10;
}
array = (T[])new Object[initCapacity];
}
public void add(T e){
if(size >= array.length){
System.out.println("MyArray It's full ");
return;
}
array[size] = e;
size++;
}
public T get(int index){
if(index<0 || index>=size){
throw new ArrayIndexOutOfBoundsException(" Array subscript out of bounds ");
}
return array[index];
}
}Here's a problem :

stay new When the object , Generic types must be replaced with concrete types , Use here Object And in the forced conversion

Insert... Into the inside Person and Student object
MyArray<Student> myArray1 = new MyArray<>(10);
myArray1.add(new Student());
MyArray<Person> myArray2 = new MyArray<>(10);
myArray2.add(new Person());When the generic parameter is specified as Student Type , If you're inserting Person Object ?

The compiler directly reports an error , Once the description type is determined , You can't insert other types of objects into it
Be careful :
Generic yes Function during compilation A mechanism of
🥎 Generic In the code The run-time between , Will be carried out in Type Erasure , The bottom layer actually uses Object Realization Of , But the user doesn't have to force the type change in the code , Let the compiler check at compile time
Check bytecode :

️ Why do we need packing
If we want to go MyArray Insert int The type of data ?

Found replacing generic parameters with int Will report a mistake , The reason is that only reference types can replace generic parameters , and int For the basic type , What to do at this time ?
The wrapper class corresponding to the basic type solves this problem
️ Packaging
️ The basic type corresponds to the packaging class
| Basic data type | Packaging |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
️ We only remember Integer and Character, Because everything else is Basic type initial caps
️ Packing and unpacking
Packing : Is to convert the basic type to the corresponding packaging type
int i = 10;
Integer in1 = Integer.valueOf(i);
Integer in2 = new Integer(i);Unpacking : Is to convert the package type to the corresponding basic type
Integer in3 = new Integer(10);
int a = in3.intValue();Automatic packing and unpacking
It can be seen from the above packing and unpacking operations , Packing and unpacking increase the amount of tedious code for us , So in order to reduce the burden of development ,Java It provides automatic packing and unpacking mechanism
int n = 10;
Integer in6 = n; // Automatic boxing
int m = in6; // Automatic dismantling 
Classic interview questions
See what the following code will output ?
public class test2 {
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a==b);
System.out.println(c==d);
}
}

Why is that ?
️️ to glance at Integer Bottom source :

Find out Integer The bottom layer maintains an array , The range of this array value is [-128,127], If Integet The value of the object is in this range , Directly from cache Take in array , Similar to string constant pool , Namely Integer The reference of type directly points to the address of the corresponding value of the array , If Integer The value of the object exceeds this range , New objects will be created
Simple summary :[-128,127],Integer Direct comparison value , Beyond this range, new objects will be created
Look at the question above :

边栏推荐
- [Yugong series] June 2022 Net architecture class 078 worker cluster of distributed middleware schedulemaster
- This "invisible" robot may be your future colleague
- With a lamp inserted in the nostril, the IQ has risen and become popular in Silicon Valley. 30000 yuan is enough
- After reading the book reading methods
- Talk about data center network again
- 真香,华为主动离职也给 N+1
- 【sql语句基础】——删(delete) /改(update)
- How the autorunner automated test tool creates a project -alltesting | Zezhong cloud test
- Streaking? Baa!
- leetcode785. 判断二分图(中等)
猜你喜欢

再聊数据中心网络

Talk about data center network again

leetcode684. 冗余连接(中等)

Toolbar details of user interface - autorunner automated test tool

基于ssm框架实现的企业进销存管理系统【源码+数据库+毕设】

PyQt5 使QPlainTextEdit控件支持行号显示

电脑下面的任务栏怎么显示打开的程序

Princeton Dengjia student's personal account: must I have a doctorate? No, I can also be an applied scientist in a large factory as an undergraduate

Yiwenjiaohui your database system tuning
![[Yugong series] June 2022 Net architecture class 079 cluster principle of distributed middleware schedulemaster](/img/bc/694f8baec114cc3f6e35c4c76c29f0.png)
[Yugong series] June 2022 Net architecture class 079 cluster principle of distributed middleware schedulemaster
随机推荐
Collection | can explain the development and common methods of machine learning!
Classmate, have you heard of mot?
Time processing logic for the last 7 days, the last 10 days, and the last 90 days
Talk about data center network again
最近7天,最近10天,最近90天时间处理逻辑
From repeatedly rejected manuscripts to post-90s assistant professor, Wang Hao of Rutgers University: curiosity drives me to constantly explore
(湖南科技大学oj作业)问题 G: 串的模式匹配
1267_FreeRTOS启动第一个任务接口prvPortStartFirstTask实现分析
Question ac: Horse Vaulting in Chinese chess
项目工作区创建步骤-泽众AR自动化测试工具
With a lamp inserted in the nostril, the IQ has risen and become popular in Silicon Valley. 30000 yuan is enough
Db4ai: database driven AI
List和Dict数据类型作用详解
推开混合云市场大门,Lenovo xCloud的破局之道
Using cloud DB to build app quick start -server
one hundred and twenty-three thousand one hundred and twenty-three
Discussion on opengauss parallel decoding
PostgreSQL create table
Data enhancement
想学好ArrayList,看完这篇就够了