Example Analysis of generics and wrapper classes in Java
This article mainly introduces the example analysis of generics and wrappers in Java, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.
1. Preliminary knowledge-introduction of generics (Generic) 1.1 generics
The sequence table that we have implemented before is to save a certain type of element (such as int)
Sample code:
Public class MyArrayList {private int [] array; / / saves the elements of the sequential table, all of which are of type int private int size; / / the number of data stored in memory of the sequential table public MyArrayList () {this.array=new int [10];} public void add (int val) {/ / insert this.array [size] = val; this.size++ } public int get (int index) {/ / get the element of index location return this.array [index];}.}
But if you write this way, the sequential table can only store elements of type int.
What if you now need to save a sequence table of references to objects of type Person? What if you need to save a reference to an object of type Book?
First of all, when we learn about polymorphism, we learn that references to base classes can point to objects of subclasses.
Second, we also know that the Object class is the ancestor of all classes in Java.
So, to solve the above problems, we can do this.
Define the element type of our sequence table as Object type so that the reference of our Object type can point to an object of type Person or an object of type Book.
Sample code:
Public class MyArrayList {private Object [] array; / / saves the elements of the sequential table, that is, the reference of Object type private int size; / / saves the memory data of the sequential table public MyArrayList () {this.array=new Object [10];} public void add (Object val) {/ / insert this.array [size] = val; this.size++ } public Object get (int index) {/ / get the element of index location return this.array [index];}.}
In this way, we are free to store references to any type of object to our sequence table.
Sample code:
MyArrayList books = new MyArrayList (); for (int item0; I