Snailclimb / Snailclimb/JavaGuide

泛型之常用的通配符有哪些?

Open
#1,692 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

perfect content
Dominant language
JavaScript
Stars
159k
Forks
46.1k
Avg merge
14h 36m
Merged PRs (30d)
6

Description

常用的通配符为: T,E,K,V,?
? 表示不确定的 Java 类型
T (type) 表示具体的一个 Java 类型
K V (key value) 分别代表 Java 键值中的 Key Value
E (element) 代表 Element

上面说的 T、E、K、V 其实都只是类型参数。而 ? 才是通配符,而且准确来说,是无限定通配符。

通配符分为有限定通配符,无限定通配符,超类型通配符。

有限定通配符:形式类似于 <? extends E>,E 如果为类,只有传入的类型参数为 E 的本身及子类才可以使用,E 如果为接口,则必须实现该接口,只能读不能写,可以用类型参数替代。

  public void addAll(DynamicArray<? extends E> array) {

 }

无限定通配符:形式为 <?>,都可以使用,只能读不能写,可以用类型参数替代。

  public void addAll(DynamicArray<?> array) {
 
 }

超类型通配符:形式为 <? super E>,可以实现对象往父类型写入,不可以用类型参数替代。

   public void copyTo(DynamicArray<? super E> dest) {

    }

简单总结
其中有限定通配符和无限定通配符只能读不能写,可以被类型参数替代。而超类型通配符可以使用对象往父类型写入,不可以用类型参数替代。

有限定通配符和无限定通配符既然能被类型参数替换,该如何选择使用的?
应该根据使用场景:

  1. 需要写入的,必须使用类型参数。
  2. 只需要读的,优先使用通配符,通配符让代码看起来更简单。

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No file or test is named. Start by locating the Java generics or wildcard documentation in the repository, then review the issue's explanations and examples against the surrounding guide. Done means the intended scope is agreed and the relevant documentation accurately explains bounded, unbounded, and lower-bounded wildcards.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.