输入参数与无界通配符 [英] Type parameter vs unbounded wildcard

查看:94
本文介绍了输入参数与无界通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从有效的Java第5章(泛型):


  //两个可能的声明交换方法
public static< E> void swap(List< E> list,int i,int j);
public static void swap(List<?> list,int i,int j);

这两个声明中的哪一个更可取,为什么?在公共API中,第二个更好,因为它更简单。您传入一个列表 - 任何列表 - 该方法交换索引元素。没有类型参数需要担心。通常,如果一个类型参数在方法声明中只出现一次,请将其替换为通配符。


我不明白为什么第二个选项对我的API客户端来说更简单?我可以将相同的参数传递给第一种和第二种方法。第二个需要通配符捕获的辅助方法。有人可以解释为什么第二个建议?
谢谢!

解决方案

Java泛型常见问题解答是一个很好的来源来回答这些问题,并且通配符vs 。泛型一个详细讨论在哪一个更好:一个具有类型参数或non-

Angelika Langer得出结论:

< blockquote>

结论:在所有这些示例中,无论您喜欢通用版本还是通配符版本,它都主要是品味和风格。通常在易于实现(通用版本通常更容易实现)和签名复杂性(通配符版本具有更少的类型参数或根本没有)之间进行权衡。

更简单的方法签名 - >更容易理解(即使两者都以相同的方式使用) - >擅长公共API(折衷:更复杂的实现)

但是整件事情是一个轻量级的问题,根据我的经验,整个API的一致性比您使用的风格更重要。


From Effective Java Chapter 5 (generics):

// Two possible declarations for the swap method
public static <E> void swap(List<E> list, int i, int j);
public static void swap(List<?> list, int i, int j);

Which of these two declarations is preferable, and why? In a public API, the second is better because it’s simpler. You pass in a list — any list — and the method swaps the indexed elements. There is no type parameter to worry about. As a rule, if a type parameter appears only once in a method declaration, replace it with a wildcard.

I don't understand, why second option is simplier for client of my API? I can pass the same parameters to first and second methods. Also second one requires helper method for wildcard capture. Could someone explains why second is recommended? Thanks!

解决方案

The Java Generics FAQ is a great source to answer these kind of questions and the "wildcard vs. generic" one is discussed at length in Which one is better: a generic method with type parameters or a non-generic method with wildcards? and the subsequent Case Studies.

Angelika Langer comes to the conclusion:

Conclusion: In all these examples it is mostly a matter of taste and style whether you prefer the generic or the wildcard version. There is usually trade-off between ease of implementation (the generic version is often easier to implement) and complexity of signature (the wildcard version has fewer type parameters or none at all).

Simpler method signature -> easier to understand (even if both are used the same way) -> good in public API (tradeoff: more complex implementation)

But the whole thing is a lightweight issue and in my experience is consistency over the whole API much more important than which style you use.

这篇关于输入参数与无界通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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