This is the 20th day of my participation in the August Text Challenge.More challenges in August

⭐ August more text challenge day 20 ⭐, review and consolidate Java😁 with friends

Code shrimp is a sand carving and funny boy who likes listening to music, playing games and writing as well as most of his friends. The days are still very long, let’s refuel our efforts together 🌈

Welcome to follow my public account: JavaCodes, the name is with Java but the scope can be more than Java field oh 😁, will share blog posts or welfare for a long time, looking forward to your attention ❤

🌈Java✨ learning Notes ✨ (13)⏩ Generic details (custom generics, wildcards…)

😉 offer yourself

Self-introduction, to everyone recommend their column 😁, welcome small partners to collect attention 😊

The small white to learn Java

MybatisPlus column

App crawler Column

PC side crawler column

Big factory interview question column


1. Generics Overview

The so-called generics allow you to define a class or interface by providing an identifier to represent the type of an attribute in the class or the return value type and parameter type of a method. This type parameter is determined (that is, passed the actual type parameter, which also becomes the type argument) when it is used (for example, when inheriting or implementing the interface, declaring variables with the type, creating objects).

** Some common generic type variables:

E: Element, mostly used in Java collection framework K: Key N: Number T: Type V: Value **


2. Generics

  • Generalization. Can T stand for any type of introduction of generics in the Java language is a major function of language, not only the type system and compiler had great changes, to support generics, and libraries also conducted a major overhaul, so many important classes, such as the collections framework, all has become the generic “, which has led to a lot of benefits.

  • Type safety. One of the main goals of generics is to improve type safety in THE AVA program. Using generics enables the compiler to know the type limits of variables, which in turn allows for a higher degree of validation of type assumptions. If you don’t use generics, you must use casts, which are unsafe and can cause ClassCast exceptions at runtime, which can be detected at compile time if you use generics.

  • Eliminate casts. Generics eliminate many casts from source code, which makes it more readable and reduces the chance of errors.

  • Backward compatibility. Generic-enabled Java compilers (such as Javac in JDK1.5) can be used to compile Generics Java programs, but existing Java programs that do not use generic extensions can still be compiled using these compilers.


3. Use generics

== If generics are not used ==

public class Main {

    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList(a);arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3); // The type is not safearrayList.add("Leathery shrimp");

        for (Object score: arrayList) {// Problem two: strong rotation may occurClassCastException
            Integer score1 = (Integer) score;
            System.out.println(score1); }}}Copy the code

== When generics are used ==

public class Main {

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList< > ();list.add(1);
        list.add(2);
        list.add(3);
//        list.add("Leathery shrimp");

        for (Integer score: list) {// Avoid strong turnsint stuscore = score;
            System.out.println(stuscore); }}}Copy the code

== When generics are used in collections ==

public class Main {

    public static void main(String[] args) {
        HashMap<String.Integer> map = new HashMap< > ();map.put("Leathery shrimp".99);
        map.put("Xiao Ming".87);
        map.put("Flower".90);

        System.out.println(map); }}Copy the code

= = = =

  • Jdk5.0 new features
  • Collection interfaces or collection classes were changed to generic structures in jdk5.0
  • When you instantiate a collection class, you can specify a specific generic type
  • If the type of the generic is not specified at instantiation time. The default type is java.lang.Object
  • Note: The type of a generic must be a class, not a primitive data type. Where you need to use basic data types, use wrapper classes instead.

Custom generics

== Custom generic classes ==

// Define the generic class publicclass Order<T> {

    String name;
    int id; // The inner structure of the class can use the generics of the classT orderT;

    public Order() {}public Order(String name, int id, T orderT) {
        this.name = name;
        this.id = id;
        this.orderT = orderT;
    }

    public T getOrderT() {
        return orderT;
    }

    public void setOrderT(T orderT) {
        this.orderT = orderT; }}Copy the code

== Test class ==

Order Order = new Order(); order.setOrderT(1);
order.setOrderT("Leathery shrimp");
Copy the code

Order<String> stringOrder = new Order<>(); stringOrder.setOrderT("Hello");
Copy the code

It is recommended to specify the generic type of the class when instantiating


4. Representation of generics in inheritance


5. The use of wildcards

== wildcard:? = =

public class Main {

    public static void print(List<? >list) {
        Iterator<? >iterator = list.iterator(a);while (iterator.hasNext()) {
            Object next = iterator.next(a);System.out.println(next); }}public static void main(String[] args) {
        List<Object> list1 = null;
        List<String> list2 = null;

        List<? >list = null;
        list = list1;
        list = list2;

        print(list1);
        print(list2); }}Copy the code

5.1 Data reading and writing requirements after using wildcards

public static void main(String[] args) {

        List<? >list = null;

        List<Object> list3 = new ArrayList<>();
        list3.add("a");
        list3.add("b");
        list3.add("c");

        list= list3; // Add (write) : yesList<? > cannot add data internally except for null //list.add("f");
        list.add(null); // Read: Data can be read. The data type is Object Object o =list.get(1);
        System.out.println(o);
    }
Copy the code


❤ finally

I am aCode pipi shrimp, a prawns lover who loves to share knowledge, will update useful blog posts in the future, looking forward to your attention!!

Creation is not easy, if this blog is helpful to you, I hope you can == one key three even oh! Thank you for your support. See you next time