Java 未绑定通配符泛型 [英] Java unbound wildcard generics

查看:32
本文介绍了Java 未绑定通配符泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bar 类中使用通配符类型的泛型比完全跳过它们有什么优势吗?

Are there any advantages of using wildcard-type generics in the Bar class over completely skipping them?

public class Foo<T> {}

public interface Bar {
    public void addFoo(Foo<?> foo);
    public Foo<?> getFoo(String name);
}

推荐答案

优势多多.

  • 它们不会像使用原始类型那样产生编译器警告
  • 它们提供了更多的类型安全性.例如,考虑一下 Foo 是否是 List.如果你使用 List 而不是 List,你可以这样做:

  • They won't produce compiler warnings like using the raw type would
  • They give more type safety. For example, consider if Foo was List instead. If you used List instead of List<?>, you could do this:

myBar.getFoo("numbers").add("some string");

即使列表仅应该包含Number.如果您返回一个 List,那么您将无法向其中添加 任何内容(除了 null),因为列表未知.

even if the list was only supposed to contain Numbers. If you returned a List<?>, then you would not be able to add anything to it (except null) since the type of list is not known.

这篇关于Java 未绑定通配符泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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