search
HomeJavajavaTutorial12.Java Basics - Wildcards

12.Java Basics - Wildcards

Feb 27, 2017 am 10:46 AM


Basic concepts


Wildcard (Wildcard), using a question mark to represent type parameters, is a Method representing the [type constraint] of [unknown type].

Generics define the data type as a parameter, and we can specify the specific type when used. But if the specific type cannot be determined when it is used, you need to rely on wildcards to solve it.

Abstractly speaking, because generics do not support covariance, wildcards are introduced to make generic types covariant.


The role of wildcards

Let’s explore the role of wildcards through two examples.

1. Do not use wildcards

ArrayList<Object> list_obj = null;
ArrayList<String> list_str = new ArrayList<String>();
// ArrayList 的元素支持  String -> Object 的强制转换list_str.add("hello");
System.out.println((Object)list_str.get(0));// 编译错误,泛型不支持协变list_obj = list_str;

Observe the code and find that:

  • The elements stored in the ArrayList are supported Upcast from String -> Object, because String is a subclass of Object.

  • A compilation error occurred when the parameter type of ArrayList was converted from String -> Object, because generics do not support covariance.


2. Use the wildcard character

ArrayList<String> list_str = new ArrayList<String>();
list_str.add("hello");

ArrayList<Integer> list_int = new ArrayList<Integer>();
list_int.add(100);

ArrayList<?> list = null;
list = list_str;
System.out.println(list.get(0));    // hellolist = list_int;
System.out.println(list.get(0));    // 100//编译错误list.add("hello");
list.add(100);

to observe the code and find:

  • in After using wildcards, it allows it to accept any type of transformation, which just solves the limitation that generics do not support covariance.

  • But at the same time, it also loses the right to add any type of object to it.


Wildcard types

There are three forms of wildcards, namely:

//1、无限定通配符 Demo<?>//2、上边界限定通配符 Demo< ? extends Number>   

//3、下边界限定通配符    Demo< ? super Number>

1. Upper bound wildcard character

Observe the following example: three classes with inheritance relationships are defined, namely Person -> Man -> Worker.

class Person{    void print(){
    }
}

class Man extends Person{    void paly(){
    }
}

class Worker extends Man{    void say(){
    }
}public class Test {
    public static void main(String[] args)  {        
    // 创建了三个 ArrayList 数组
        ArrayList<Person> personList = new ArrayList<Person>();
        ArrayList<Man> manList= new ArrayList<Man>();
        ArrayList<Worker> workerList = new ArrayList<Worker>();        
        // 限定了上界, ? 代表 Man 以及继承 Man 的类
        ArrayList<? extends Man> list  = null;

        list = manList;
        list = workerList;        // 编译错误,因为 Person 是 Man 的父类
        list = personList;        // 编译错误,因为使用了通配符就不能添加对象
        list.add(new Man());
        list.add(new Worker());        for(Man man : list){
            man.print();
            man.paly();
        }        for(Person per : list){
            per.print();
        }        // 编译错误,因为 ? 也可以代表 Man
        // 从继承我们可以知道 Worker 肯定是 Man,但 Man 不一定是 Worker。
        // for(Worker worker : list);
    }
}

2. Lower bound wildcard character

// 省略相同代码...public class Test {
    public static void main(String[] args)  {
        ArrayList<Person> personList = new ArrayList<Person>();
        ArrayList<Man> manList= new ArrayList<Man>();
        ArrayList<Worker> workList = new ArrayList<Worker>();        
        // 限定了下届, ? 代表 Man 以及 Man 的父类
        ArrayList<? super Man> list  = null;

        list = personList;
        list = manList;        // 编译错误,因为 Worker 是 Man 的子类
        list = workList;        // 编译错误,无法确定其父类对象
        // Person 继承子 Cell 类,那么用 Person 遍历就是错误的
        // for(Man man : list);
        // for(Person per : list);

        // 因为 Object 是所有类的根类,所以可以用Object来遍历
        // for(Object obj : list);
    }
}

3. Unbounded wildcard character

// 省略相同代码...public class Test {
    public static void main(String[] args)  {
        ArrayList<Person> personList = new ArrayList<Person>();
        ArrayList<Man> manList= new ArrayList<Man>();
        ArrayList<Worker> workList = new ArrayList<Worker>();        //无边界通配符
        ArrayList<?> list  = null;        //可以代表一切类型
        list = personList;
        list = manList;
        list = workList;        //为了避免类型混淆,只允许使用 Object 遍历
        for(Object obj : list); 
    }
}

The above is the content of 12.Java Basics - Wildcards. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
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
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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months 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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function