search
HomeJavajavaTutorialWhat are the differences between placeholders T and ? in java generics?

First two pieces of code:

public static <T> void show1(List<T> list){
 for (Object object : list) {
        System.out.println(object.toString());
    }
}

public static void show2(List<?> list) {
    for (Object object : list) {
        System.out.println(object);
    }
}

You can see that we use T in the show1 method. Everyone knows that this is a common way of writing generics, so T here refers to a certain type of specific Objects and list collections can only store data of the same type. If different types of data are inserted, an error will be reported.

So what do we use in the show2 method? , you can see that there is no <t></t> in front of void,? It can be expressed as a placeholder, and it does not know how many types of data will be stored in the list collection, so this shows that it is also possible to store N data types in our list.

Let’s intuitively feel the difference between the two through a piece of test code:

public static void test(){
   List<Student> list1 = new ArrayList<>();
   list1.add(new Student("zhangsan",18,0));
   list1.add(new Student("lisi",28,0));
   list1.add(new Student("wangwu",24,1));
   //这里如果add(new Teacher(...));就会报错,因为我们已经给List指定了数据类型为Student
   show1(list1);

   System.out.println("************分割线**************");

   //这里我们并没有给List指定具体的数据类型,可以存放多种类型数据
   List list2 = new ArrayList<>();
   list2.add(new Student("zhaoliu",22,1));
   list2.add(new Teacher("sunba",30,0));
   show2(list2);
}

Let’s take a look at the running results:

Student{name='zhangsan ', age=18, sex=0}
Student{name='lisi', age=28, sex=0}
Student{name='wangwu', age=24, sex=1}
************Separation line******************
Student{name='zhaoliu', age=22, sex=1}
Teacher{name='sunba', age=30, sex=0}

You can see the difference from show1 from the show2 method. List2 stores two types of Student and Teacher. The same can be done Output data, so this is the difference between T and ?~ Friends, do you understand?

Let’s take a look? Extended writing method:

List extends data type> list

public static void show3(List<? extends Teacher> list) {
    for (Object object : list) {
        System.out.println(object);
    }
}

List extends Teacher> list This writing method means that it can Receive a list collection of Teacher and its subclass data types, and write a test method show3(list2);Try:

Student{name=&#39;zhaoliu&#39;, age=22, sex=1}
Teacher{name=&#39;sunba&#39;, age=30, sex=0}

You can see normal output, because the data in the collection are all It is a subclass type of Teacher. What will happen if we change List extends Teacher> list to List extends Student> list?

What are the differences between placeholders T and ? in java generics?

Look at this picture carefully. We have created a new list3 and declared the data type to be Teacher. At this time, we call show3(List extends Student> list) An error will be reported immediately. The error message indicates that Teacher cannot be converted to Student, because Student is a subclass of Teacher, and we only accept Student and its subclasses, so of course an error will be reported.

List super data type> list

This way of writing means that only the specified data type and its parent class type are received, and it is also a simple way to write a piece of code Take a look at the effect:

public static void show4(List<? super Student> list) {
    for (Object object : list) {
        System.out.println(object);
    }
}

It can be seen that what we receive is the collection of Student and its parent class. We write two collection data and then call it to try.

List list4 = new ArrayList<>();
list4.add(new Student("sunba",30,0));
list4.add(new Teacher("zhaoliu",22,1));
show4(list4);

Insert a Student and Teacher object into the list and see the result:

Student{name=&#39;sunba&#39;, age=30, sex=0}
Teacher{name=&#39;zhaoliu&#39;, age=22, sex=1}

Nothing wrong, it runs normally and outputs.

Let’s take a look at what will happen if we pass a collection of Student subclasses

What are the differences between placeholders T and ? in java generics?

You can see the same as before, it will The error is reported for the same reason, thinking that we have defined a data type that can only receive Student and its parent class.

Finally let’s look at a situation

If I don’t specify a data type when defining List, and insert a Child, Student, Teacher, or call show4(List super Student> list), will an error be reported? If no error is reported, what will be the result?

What are the differences between placeholders T and ? in java generics?

You can see that no error is reported because list can store multiple data types. So what will be the result when calling the show4 method?

What are the differences between placeholders T and ? in java generics?

You can see that the program runs normally and outputs results. Note that what we receive is the Student and its parent class object data types, because our Child inherits from Student. Therefore, the program automatically converts our Child into the parent class Student for output, so everyone should pay attention to this, and it will automatically convert upward.

The above is the detailed content of What are the differences between placeholders T and ? in java generics?. 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
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool