国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaBase Detailed introduction to java generics

Detailed introduction to java generics

Nov 27, 2019 pm 02:31 PM
java

Detailed introduction to java generics

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, it is directly restricted that the list collection can only contain String type elements. , so there is no need to perform forced type conversion at //2, because at this time, the collection can remember the type information of the element, and the compiler can already confirm that it is a String type.

Combined with the above generic definition, we know that in List, String is a type actual parameter, that is to say, the corresponding List interface must contain type parameters. And the return result of the get() method is also directly the type of this formal parameter (that is, the corresponding incoming type actual parameter). Let’s take a look at the specific definition of the List interface:

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 represents the type parameter and can receive specific Type arguments, and in this interface definition, wherever E appears, it represents the same type argument received from the outside.

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和Box實(shí)際上都是Box類型,現(xiàn)在需要繼續(xù)探討一個(gè)問題,那么在邏輯上,類似于Box和Box是否可以看成具有父子關(guān)系的泛型類型呢?

為了弄清這個(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) in the t ype GenericTest is not applicable for the arguments (Box)。顯然,通過提示信息,我們知道Box在邏輯上不能視為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在邏輯上可以視為Box的父類,那么//1和//2處將不會(huì)有錯(cuò)誤提示了,那么問題就出來了,通過getData()方法取出數(shù)據(jù)時(shí)到底是什么類型呢?Integer? Float? 還是Number?且由于在編程過程中的順序不可控性,導(dǎo)致在必要的時(shí)候必須要進(jìn)行類型判斷,且進(jìn)行強(qiáng)制類型轉(zhuǎn)換。顯然,這與泛型的理念矛盾,因此,在邏輯上Box不能視為Box的父類。

好,那我們回過頭來繼續(xù)看“類型通配符”中的第一個(gè)例子,我們知道其具體的錯(cuò)誤提示的深層次原因了。那么如何解決呢?總部能再定義一個(gè)新的函數(shù)吧。

這和Java中的多態(tài)理念顯然是違背的,因此,我們需要一個(gè)在邏輯上可以用來表示同時(shí)是Box和Box的父類的一個(gè)引用類型,由此,類型通配符應(yīng)運(yùn)而生。

類型通配符一般是使用 ? 代替具體的類型實(shí)參。注意了,此處是類型實(shí)參,而不是類型形參!且Box在邏輯上是Box、Box...等所有Box<具體類型實(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);
    }

    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形式定義,相對(duì)應(yīng)的,類型通配符下限為Box形式,其含義與類型通配符上限正好相反,在此不作過多闡述了。

更多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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1501
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

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.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

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

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

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

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

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

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

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

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

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

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

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.

Java Concurrency Utilities: ExecutorService and Fork/Join Java Concurrency Utilities: ExecutorService and Fork/Join Aug 03, 2025 am 01:54 AM

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

See all articles