Introduction and use of generics in Java

Posted by sockit2em on Mon, 02 Dec 2019 01:13:31 +0100

Introduction: Recently Mobai has made a blog of his own, with git + hexo + node.js as the technical point. I will give a blog tutorial in a few days. Interested partners can try to make their own blog when they come. I put the link of my blog in the end of reading the original text. Interested partners can visit it, because there are many contents involved, I may need about one to two weeks Only then can I finish the blog tutorial, so I need you to wait patiently. The blog tutorial will be very detailed, to ensure that you can develop your own blog from scratch! Today, I will mainly tell you about the use of generics in Java and what generics are? Please see the text below

Generic overview We all know that collections (list,map...) in Java can store any Object. As long as objects are stored in collections, they will be promoted to Object type. When we are taking out every Object and doing the corresponding operation, we must adopt the type conversion. Look at the following sample code

package com.mobaijun;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class GeneriDemo1{
    public static void main(String[] args) {
        Collection coll = new ArrayList();
        coll.add("mobai");
        coll.add("Ink white");
        coll.add(5);//Since the collection has no restrictions, any type can be stored in it
        Iterator it = coll.iterator();
        while (it.hasNext()) {
            //To print the length of each String, you need to convert the iterated object to String type
            String str = (String) it.next();
            System.out.println(str.length());
        }
    }
}

We can see that the console printing result is an exception, and the different information is as follows:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

The Demo encountered a java.lang.ClassCastException at run time. The main class could not be found or could not be loaded. Why do type conversion exceptions occur? Let's analyze: because any type of element in the collection can be stored. Causes a strong transition on fetch to raise a runtime ClassCastException. How to solve this problem? Although Collection can store various objects, in fact, Collection usually only stores objects of the same type. For example, they are all storage string objects. Therefore, after JDK5, generic syntax has been added, which allows you to specify classes or methods to support generics when designing API. In this way, when we use API, it will become more concise and get syntax check at compile time. In a word, generics can use unknown types in classes or methods in advance

So what are the benefits of using generics? See the following code to experience the benefits of generics:

package com.mobaijun;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class GeneriDemo2 {
    public static void main(String[] args) {
        Collection<string> list = new ArrayList<string>();
        list.add("mobai");
        list.add("Ink white");
        // list.add(5);
        // When the set specifies the type, the storage type is inconsistent, and an error is reported        
        // The collection has specified the type of element to store, so when using the iterator, the iterator will also know the type of traversal element
        Iterator<string> it = list.iterator();
        while (it.hasNext()) {
            String str = it.next();
            //When you use iterator < String > to control element types, you don't need to force a transition. The obtained element is the String type directly            
            System.out.println(str.length());
        }
    }
}

The definition and use of generics Generics are used to flexibly apply data types to different classes, methods and interfaces. Pass the data type as a parameter. Definition format of generics: >Modifier class class name < variable representing generic > {} Example code:

class ArrayList<e> {
    public boolean add(E e) {
    }
    public E get(int index) {
    }
}

Generics are not specific when they are defined, but only when they are used. Determine the specific data type of the generic when you use it. Use generics: when to determine generics. Determine generics when creating objects For example, ArrayList < string > List = new ArrayList < string > (); At this point, the value of variable E is the String type, so our type can be understood as

class ArrayList<string> {
    public boolean add(String e) {
    }
    public String get(int index) {
    }
}

For example, ArrayList < integer > List = new ArrayList < integer > (); At this point, the value of variable E is of type Integer, so our type can be understood as:

class ArrayList<integer> {
    public boolean add(Integer e) {
    }
    public Integer get(int index) {
    }
}

generic method Example code:

public class MyGenericMethod {
    public <mvp> void show(MVP mvp) {
        System.out.println(mvp.getClass());
    }

    public <mvp> MVP show2(MVP mvp) {
        return mvp;
    }
}

When the method is called, the generic type is specified: the code is as follows

package com.mobaijun;

public class GeneriDemo3 {
    public static void main(String[] args) {
        MyGenericMethod my = new MyGenericMethod();
        my.show("Ink white");
        my.show(18);
        my.show(178.0);
    }
}

Generic interface Example code:

package com.mobaijun;

public interface MyGenericInterface<e> {
    public abstract void add(E e);
    public abstract E gitE();
}

Let's look at how to use generics if you want to define a class: Example code:

package com.mobaijun;

public class MyImpl implements MyGenericInterface<string>{
    [@Override](https://my.oschina.net/u/1162528)
    public void add(String s) {
        // ellipsis
    }

    [@Override](https://my.oschina.net/u/1162528)
    public String gitE() {
        return null;
    }
}

At the beginning of the class, we defined the generic type. Then, the value of generic e is String; If you are not sure about the type of the generic, you can determine the type of the generic until you create the object

package com.mobaijun;

/**
 * Uncertain type of generics
 * [@param](https://my.oschina.net/u/2303379) <e>
 */
public class MyImpl2<e> implements MyGenericInterface<e> {

    [@Override](https://my.oschina.net/u/1162528)
    public void add(E e) {

    }

    [@Override](https://my.oschina.net/u/1162528)
    public E gitE() {
        return null;
    }
}

Determine the type of generics when creating objects

package com.mobaijun;

/**
 * Determine the type of generics when creating objects
 */
public class GenericInterface  {
    public static void main(String[] args) {
        MyImpl2<string> my = new MyImpl2<string>();
        my.add("Ink white");
    }
}

There is one last knowledge point about generics, which is the wildcard of generics When a generic class or interface is used, the generic type in the data passed is uncertain and can be represented by the wildcard character <! --? >. However, once the generic wildcard is used, only the common methods in the Object class can be used, and the element's own methods in the collection cannot be used. The basic use of wildcards is as follows Generic wildcard: when you don't know what type to use to receive, you can use?,? To indicate unknown wildcard. At this time, data can only be accepted and cannot be stored in the collection. Example code:

package com.mobaijun;

import java.util.ArrayList;
import java.util.Collection;

public class MyDemo {
    public static void main(String[] args) {
        Collection<integer> c = new ArrayList<integer>();
       getElement(c);

       Collection<string> c2 = new ArrayList<string>();
       getElement(c2);
    }

    /**
     * The "? In the wildcard represents any type of data
     * Note that generics do not have inheritance relationships,
     *      Collection<object> c2 = new ArrayList<string>();Wrong example
     * @param collection
     */
    public static void getElement(Collection<!--?--> collection){

    }
}

Advanced use of wildcards When you set generics before, you can actually set them at will, as long as they are classes. However, in JAVA generics, you can specify an upper and lower limit of generics. Upper limit of generics: Format: type name <! -- extensions class -- > object name meaning: only this type and its subclasses can be received Lower bound of generics: Format: type name <! -- super class > object name meaning: only this type and its parent type can be received For example, now we know the Object class, String class, Number class and Integer class, where Number is the parent class of Integer

package com.mobaijun;

import java.util.ArrayList;
import java.util.Collection;

public class MyDemo4 {
    public static void main(String[] args) {
        Collection<integer> c1 = new ArrayList<integer>();
        Collection<string> c2 = new ArrayList<string>();
        Collection<number> c3 = new ArrayList<number>();
        Collection<object> c4 = new ArrayList<object>();

        getElementOne(c1);
        getElementOne(c2);// Compile and report errors
        getElementOne(c3);
        getElementOne(c4);// Compile and report errors

        getElementTow(c1);// Compile and report errors
        getElementTow(c2);// Compile and report errors
        getElementTow(c3);
        getElementTow(c4);
    }
    // Upper limit of generics: at this time, generics? Must be subclasses of type Number or Number
    public static void getElementOne(Collection<!--? extends Number--> collection){}
    // Lower limit of generics: the generics? At this time must be the parent class of Number type or Number type
    public static void getElementTow(Collection<!--? super Number--> collection){}
}

The above is the whole content of generics, if it helps you, please click at the end of the article to have a good day, come on!!!

> this article starts with the public number [frame master, ID:mohu121]. Please remark the source </object></object></number></number></string></string></integer></integer></string></object></string></string></integer></integer></string></string></e></e></e></string></e></mvp ></mvp></integer></integer></integer></string></string></string></e></ for generics. Quantity > < string > < string > < string > < string > < string >

Topics: Programming Java git