Table of Contents
Basic concepts
The role of wildcards
1. Do not use wildcards
2. Use the wildcard character
Wildcard types
1. Upper bound wildcard character
2. Lower bound wildcard character
3. Unbounded wildcard character
Home Java javaTutorial 12.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;
Copy after login

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);
Copy after login

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>
Copy after login

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);
    }
}
Copy after login

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);
    }
}
Copy after login

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); 
    }
}
Copy after login

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 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

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 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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles