1. The introduction of the concept of generics (why are generics needed)? (Recommended: java video tutorial)
First, let’s look at the following short code:
public class GenericTest { public static void main(String[] args) { List list = new ArrayList(); list.add("qqyumidi"); list.add("corn"); list.add(100); for (int i = 0; i < list.size(); i++) { String name = (String) list.get(i); // 1 System.out.println("name:" + name); } } }
defines a collection of List type. Two values ??of type String are added to it, followed by a value of type Integer. This is completely allowed, because the default type of list is Object.
In subsequent loops, errors similar to //1 may easily occur due to forgetting to add Integer type values ??to the list before or other encoding reasons. Because the compilation phase is normal, but a "java.lang.ClassCastException" exception occurs during runtime. Therefore, such errors are difficult to detect during coding.
During the above coding process, we found that there are two main problems:
1. When we put an object into a collection, the collection will not remember the type of the object. When this object is taken out from the collection again, the compiled type of the object changes to the Object type, but its runtime type is still its own type.
2. Therefore, when taking out the collection elements at //1, artificial forced type conversion to a specific target type is required, and the "java.lang.ClassCastException" exception is prone to occur.
So is there any way to enable the collection to remember the types of elements in the collection, and to achieve the goal that as long as there are no problems during compilation, "java.lang.ClassCastException" exceptions will not occur during runtime? The answer is to use generics.
2. What are generics?
Generics, that is, "parameterized types". When it comes to parameters, the most familiar thing is that there are formal parameters when defining a method, and then the actual parameters are passed when calling this method.
So how do you understand parameterized types? As the name suggests, the type is parameterized from the original specific type, similar to the variable parameters in the method. At this time, the type is also defined in the form of a parameter (which can be called a type parameter), and then the specific type is passed in when using/calling type (type argument).
It seems a bit complicated. First, let’s take a look at the above example using generic writing.
public class GenericTest { public static void main(String[] args) { /* List list = new ArrayList(); list.add("qqyumidi"); list.add("corn"); list.add(100); */ List<String> list = new ArrayList<String>(); list.add("qqyumidi"); list.add("corn"); //list.add(100); // 1 提示編譯錯(cuò)誤 for (int i = 0; i < list.size(); i++) { String name = list.get(i); // 2 System.out.println("name:" + name); } } }
After adopting the generic writing method, a compilation error will occur when trying to add an Integer type object at //1. Through List
Combined with the above generic definition, we know that in List
public interface List<E> extends Collection<E> { int size(); boolean isEmpty(); boolean contains(Object o); Iterator<E> iterator(); Object[] toArray(); <T> T[] toArray(T[] a); boolean add(E e); boolean remove(Object o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); boolean addAll(int index, Collection<? extends E> c); boolean removeAll(Collection<?> c); boolean retainAll(Collection<?> c); void clear(); boolean equals(Object o); int hashCode(); E get(int index); E set(int index, E element); void add(int index, E element); E remove(int index); int indexOf(Object o); int lastIndexOf(Object o); ListIterator<E> listIterator(); ListIterator<E> listIterator(int index); List<E> subList(int fromIndex, int toIndex); }
We can see that after adopting the generic definition in the List interface, the E in
Naturally, ArrayList is the implementation class of the List interface, and its definition form is:
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } public E get(int index) { rangeCheck(index); checkForComodification(); return ArrayList.this.elementData(offset + index); } //...省略掉其他具體的定義過程 }
From this, we understand from the source code perspective why there is a compilation error when adding an Integer type object at //1 , and the type obtained by get() at //2 is directly the String type.
3. Customized generic interfaces, generic classes and generic methods
From the above content, everyone has understood the specific operation process of generics. We also know that interfaces, classes and methods can also be defined using generics and used accordingly. Yes, in specific use, it can be divided into generic interfaces, generic classes and generic methods.
Customized generic interfaces, generic classes and generic methods are similar to List and ArrayList in the above Java source code. As follows, we look at the simplest definition of generic classes and methods:
public class GenericTest { public static void main(String[] args) { Box<String> name = new Box<String>("corn"); System.out.println("name:" + name.getData()); } } class Box<T> { private T data; public Box() { } public Box(T data) { this.data = data; } public T getData() { return data; } }
In the definition process of generic interfaces, generic classes and generic methods, we commonly see T, E, K, V Parameters of the same form are often used to represent generic parameters because they receive type arguments passed in from external uses. So for different type arguments passed in, are the types of the corresponding object instances generated the same?
public class GenericTest { public static void main(String[] args) { Box<String> name = new Box<String>("corn"); Box<Integer> age = new Box<Integer>(712); System.out.println("name class:" + name.getClass()); // com.qqyumidi.Box System.out.println("age class:" + age.getClass()); // com.qqyumidi.Box System.out.println(name.getClass() == age.getClass()); // true } }
From this, we found that when using generic classes, although different generic arguments are passed in, different types are not actually generated. There is only one generic class in memory, which is the original most basic type (Box in this example). Of course, logically we can understand it as multiple different generic types.
The reason is that the purpose of the concept of generics in Java is that it only affects the code compilation stage. During the compilation process, after the generic results are correctly verified, the generics will be Relevant information is erased, that is to say, the successfully compiled class file does not contain any generic information. Generic information does not enter the runtime stage.
對(duì)此總結(jié)成一句話:泛型類型在邏輯上看以看成是多個(gè)不同的類型,實(shí)際上都是相同的基本類型。
四.類型通配符
接著上面的結(jié)論,我們知道,Box
為了弄清這個(gè)問題,我們繼續(xù)看下下面這個(gè)例子:
public class GenericTest { public static void main(String[] args) { Box<Number> name = new Box<Number>(99); Box<Integer> age = new Box<Integer>(712); getData(name); //The method getData(Box<Number>) in the type GenericTest is //not applicable for the arguments (Box<Integer>) getData(age); // 1 } public static void getData(Box<Number> data){ System.out.println("data :" + data.getData()); } }
我們發(fā)現(xiàn),在代碼//1處出現(xiàn)了錯(cuò)誤提示信息:The method getData(Box
public class GenericTest { public static void main(String[] args) { Box<Integer> a = new Box<Integer>(712); Box<Number> b = a; // 1 Box<Float> f = new Box<Float>(3.14f); b.setData(f); // 2 } public static void getData(Box<Number> data) { System.out.println("data :" + data.getData()); } } class Box<T> { private T data; public Box() { } public Box(T data) { setData(data); } public T getData() { return data; } public void setData(T data) { this.data = data; } }
這個(gè)例子中,顯然//1和//2處肯定會(huì)出現(xiàn)錯(cuò)誤提示的。在此我們可以使用反證法來進(jìn)行說明。
假設(shè)Box
好,那我們回過頭來繼續(xù)看“類型通配符”中的第一個(gè)例子,我們知道其具體的錯(cuò)誤提示的深層次原因了。那么如何解決呢?總部能再定義一個(gè)新的函數(shù)吧。
這和Java中的多態(tài)理念顯然是違背的,因此,我們需要一個(gè)在邏輯上可以用來表示同時(shí)是Box
類型通配符一般是使用 ? 代替具體的類型實(shí)參。注意了,此處是類型實(shí)參,而不是類型形參!且Box>在邏輯上是Box
public class GenericTest { public static void main(String[] args) { Box<String> name = new Box<String>("corn"); Box<Integer> age = new Box<Integer>(712); Box<Number> number = new Box<Number>(314); getData(name); getData(age); getData(number); } public static void getData(Box<?> data) { System.out.println("data :" + data.getData()); } }
有時(shí)候,我們還可能聽到類型通配符上限和類型通配符下限。具體有是怎么樣的呢?
在上面的例子中,如果需要定義一個(gè)功能類似于getData()的方法,但對(duì)類型實(shí)參又有進(jìn)一步的限制:只能是Number類及其子類。此時(shí),需要用到類型通配符上限。
public class GenericTest { public static void main(String[] args) { Box<String> name = new Box<String>("corn"); Box<Integer> age = new Box<Integer>(712); Box<Number> number = new Box<Number>(314); getData(name); getData(age); getData(number); //getUpperNumberData(name); // 1 getUpperNumberData(age); // 2 getUpperNumberData(number); // 3 } public static void getData(Box<?> data) { System.out.println("data :" + data.getData()); } public static void getUpperNumberData(Box<? extends Number> data){ System.out.println("data :" + data.getData()); } }
此時(shí),顯然,在代碼//1處調(diào)用將出現(xiàn)錯(cuò)誤提示,而//2 //3處調(diào)用正常。
類型通配符上限通過形如Box extends Number>形式定義,相對(duì)應(yīng)的,類型通配符下限為Box super Number>形式,其含義與類型通配符上限正好相反,在此不作過多闡述了。
更多java知識(shí)請(qǐng)關(guān)注java基礎(chǔ)教程欄目。
The above is the detailed content of Detailed introduction to java generics. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

ExecutorService is suitable for asynchronous execution of independent tasks, such as I/O operations or timing tasks, using thread pool to manage concurrency, submit Runnable or Callable tasks through submit, and obtain results with Future. Pay attention to the risk of unbounded queues and explicitly close the thread pool; 2. The Fork/Join framework is designed for split-and-governance CPU-intensive tasks, based on partitioning and controversy methods and work-stealing algorithms, and realizes recursive splitting of tasks through RecursiveTask or RecursiveAction, which is scheduled and executed by ForkJoinPool. It is suitable for large array summation and sorting scenarios. The split threshold should be set reasonably to avoid overhead; 3. Selection basis: Independent
