有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

关于Java中泛型的查询

我有一个只读方法,应该可以

1. Map<Date, List<X>>

或者

2. Map<Date, List<Y>>

作为一个参数

在这里,我有以下两个选项来定义这个方法

A. private <T> List<Date> myMethod(Map<Date, List<T>> map)
B. private List<Date> myMethod(Map<Date, List<?>> map)

对我来说都很好,哪一个更好

谢谢


共 (2) 个答案

  1. # 1 楼答案

    JLS

    <T> boolean addAll(Collection<T> c)
    

    This version is sufficiently flexible, but note that the type parameter is used only once in the signature. This reflects the fact that the type parameter is not being used to express any kind of interdependency between the type(s) of the argument(s), the return type and/or throws type. In the absence of such interdependency, generic methods are considered bad style, and wildcards are preferred.

  2. # 2 楼答案

    第一个选项允许您在需要时访问T类型(例如,如果您需要将某些内容转换为T或类似的内容)。对于后者,你只需声明你根本不在乎List包含什么类型的元素