为什么将变量声明为通配符类型 [英] Why declare a variable as a wildcard type

查看:90
本文介绍了为什么将变量声明为通配符类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java教程中,有时是书面的东西像这样:

In the Java tutorials, it is sometimes written things like this :

Set<?> unknownSet = new HashSet<String>();

虽然我了解在类定义和方法中使用类型参数和通配符的好处,但我想知道以下几点:

While I understand the benefits of using type parameters and wildcards in class definitions and methods, I am wondering the following:

  • 为变量提供包含通配符的类型有什么好处?
  • 在现实生活中,人们会这样做吗?何时?

推荐答案

通配符仅在方法参数声明中真正有用,因为它们会增加可接受的参数类型的范围,例如:

Wildcards are only really useful in method parameter declarations, as they increase the range of acceptable parameter types, for example:

void original(List<Number> list) { /* ... */ }
void withUpperWildcard(List<? extends Number> list) { /* ... */ }
void withLowerWildcard(List<? super Number> list) { /* ... */ }

original(new ArrayList<Number>());       // OK.
original(new ArrayList<Integer>());      // Compiler-error.
original(new ArrayList<Object>());      // Compiler-error.

withUpperWildcard(new ArrayList<Number>());  // OK.
withUpperWildcard(new ArrayList<Integer>());  // OK.

withLowerWildcard(new ArrayList<Number>());  // OK.
withLowerWildcard(new ArrayList<Object>());  // OK.

返回类型的通配符会使类用户的生活变得困难(或变得凌乱),因为您必须传播通配符,或进行明确的工作以使它们消失,例如:

Wildcards in return types make life difficult (or, rather, messy) for users of your class, since you have to either propagate them, or do explicit work to make them go away, for example:

List<? extends Number> method() { /* ... */ }

// Compiler error.
List<Number> list1 = method();
// OK, but yuk!
List<? extends Number> list2 = method();         
// OK, but the list gets copied.
List<Number> list3 = new ArrayList<Number>(method());  

不需要使用局部变量中的通配符(接受通配符返回方法的结果除外).

Wildcards in your local variables just aren't necessary (except to accept the results of wildcard-returning methods).

引用有效的Java 2nd Ed:

To quote Effective Java 2nd Ed:

如果类的用户必须考虑通配符类型,则该类的API可能有问题.

If the user of a class has to think about wildcard types, there is probably something wrong with the class’s API.

这篇关于为什么将变量声明为通配符类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆