gpt4 book ai didi

java - 问号是什么? (不与 :) in Java means 一起使用

转载 作者:行者123 更新时间:2023-11-29 05:17:20 24 4
gpt4 key购买 nike

我看到了一段代码:

public abstract List<Class<? extends Pet>> types();

(前面表示Dog类和Cat类继承自Pet类)问号是什么?是指这里吗?

最佳答案

这称为通配符,在定义泛型类型时很有用。从 documentation 看这个例子:

Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error

Since we don't know what the element type of c stands for, we cannot add objects to it. The add() method takes arguments of type E, the element type of the collection. When the actual type parameter is ?, it stands for some unknown type. Any parameter we pass to add would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.

同样来自伟大的 Java 泛型 FAQ :

A wildcard describes a family of types. There are 3 different flavors of wildcards:

  • "? "- 无限通配符。它代表所有类型的家庭。
  • "? extends Type "- 带有上限的通配符。它代表所有类型的家族,这些类型是 Type 的子类型,类型 Type 被包括在内。
  • "? super Type "- 具有下限的通配符。它代表所有类型的家族,这些类型是 Type 的父类(super class)型,类型 Type 被包括在内。

Wildcards are used to declare so-called wildcard parameterized types, where a wildcard is used as an argument for instantiation of generic types. Wildcards are useful in situations where no or only partial knowledge about the type argument of a parameterized type is required.

关于java - 问号是什么? (不与 :) in Java means 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26071237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com