search
HomeJavajavaTutorialHow to use wildcards to enhance Java's generic performance

    Use wildcards to enhance generics

    1. Question

    Generics are an important feature of JAVA. Using generic programming, you can Code reuse rate is improved.

    Implementation: Use wildcards in generic methods

    2. Problem-solving ideas

    Create a class: WildcardsTest.

    Create a method getMiddle() for getting the middle value of a given list.

    In generics, use "?" as a wildcard character. The use of wildcard characters is similar to that of ordinary type parameters. For example, wildcard characters can use the extends keyword to set the upper limit of the value. For example,

    extends Number>

    indicates that Byte, Double, Float, and Integer are suitable for this type parameter.

    Also, there is an upper limit and a lower limit, such as

    super Number>

    w means that the type parameter is the parent of the Number class Class, such as Object.

    3. Detailed code explanation

    package com.xiaoxuzhu;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    /**
     * Description:
     *
     * @author xiaoxuzhu
     * @version 1.0
     *
     * <pre class="brush:php;toolbar:false">
     * 修改记录:
     * 修改后版本	        修改人		修改日期			修改内容
     * 2022/5/10.1	    xiaoxuzhu		2022/5/10		    Create
     * 
     * @date 2022/5/10  */ public class WildcardsTest {     public static Object getMiddle(List extends Number> list) {         return list.get(list.size() / 2);     }     public static void main(String[] args) {         List ints = new ArrayList();         ints.add(1);         ints.add(2);         ints.add(3);         System.out.print("整型列表的元素:");         System.out.println(Arrays.toString(ints.toArray()));         System.out.println("整型列表的中间数:" + getMiddle(ints));         List doubles = new ArrayList();         doubles.add(1.1);         doubles.add(2.2);         doubles.add(3.3);         System.out.print("浮点列表的元素:");         System.out.println(Arrays.toString(doubles.toArray()));         System.out.println("浮点列表的中间数:" + getMiddle(doubles));     } }

    How to use wildcards to enhance Javas generic performance

    Supplementary knowledge points

    Generics

    You can use , , , etc. to declare generics. The declaration method of limits the scope of T, and T can only be a subclass of User.

    1. Parameter types are used in the creation of classes, generic classes.

    2. Parameter types are used in the creation of interfaces, generic interfaces.

    3. Parameter types are used in the creation of methods, generic methods. Note the declaration position of the generic , after the method's modifier and before the return value type.

    ? Type wildcard character

    Several forms of wildcard character:

    1. Unlimited wildcard character, >.

    2. Upper limit wildcard, extends User>. Indicates that the parameter type can only be a subclass of User.

    3. Lower limit wildcard, super User>. Indicates that the parameter type can only be the parent class of User.

    public class P<T> {
      private T t;
      public T getT(){
        return t;
      }
    
      //通配符
      //设置指定类型的范围,超过范围就会报错
      //extends : 指定范围必须是其(这里是List)子类
      public void set(P<? extends List> list){
        return;
      }
    
      //super : 指定类型必须是其(这里是List)父类
      public void setSuper(P<? super List> list){
        return;
      }
    
      public static void main(String[] args) {
        new P<String>(); //T会被替换成String
        new P<Integer>(); //T会被替换成Integer
        Person<String,List,Double,User> person = new Person<String,List,Double,User>();//T会被替换成String,B会被替换成List...
        person.eat("鱼");
      }
    }
    class User<T extends P>{//这里给类的泛型指定范围,T必须要继承类P。
    
    }
    //一个类可以同时指定多个泛型
    class Person<T,B,S,N>{
      private T t;
      private B b;
      private S s;
      private N n;
      public void eat(T t){
        this.t = t;
        System.out.println("我正在吃"+this.t);
      }
    }

    The declaration of generics indicates that an unknown data type is to be used in the creation of classes, interfaces, and methods. It can be of type Integer or String. Just define its type as T, S or N, etc.

    When instantiating, you must declare what type T is.

    When defining the usage method of a generic object, it is not known what type T is. It may be a String type or an Integer type. If T is defined as a certain generic data type, the parameters can only be of this data type. At this time, wildcards are used instead of certain generic data types.

    Use generics and wildcards to improve code reusability.

    If an object is divided into two parts: declaration and use. Generics focus on code reuse in type declaration, while wildcards focus on code reuse in usage. Generics are used to define uncertainty about internal data types, and wildcards are used to define uncertainty about the type of objects used.

    The above is the detailed content of How to use wildcards to enhance Java's generic performance. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

    The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

    How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

    The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

    How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

    The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

    How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

    The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

    How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

    Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

    See all articles

    Hot AI Tools

    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.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment