[英]How can I create a generic method signature for “any map entry” value in the parameter list and/or return type?
In the code that I'm currently refactoring, there exists a similar operation on a bunch of Maps
. 在我当前重构的代码中,一堆
Maps
上存在类似的操作。 All Maps are of the following type: 所有地图的类型如下:
Map<<SomeType>,Double> myMap;
They undergo the same transformation and are converted to: 它们经历相同的转换,并转换为:
TreeMap<Integer, <SomeType>> transformedMap;
I wanted to know if it's possible to create a generic method that looks something like this: 我想知道是否可以创建如下所示的通用方法:
public TreeMap<Integer, <T>> transformMap(Map<<T>,Double> myMap){...}
What's the way to accomplish this? 有什么方法可以做到这一点?
SomeType
could be any kind of object/collection. SomeType
可以是任何类型的对象/集合。 I could replace <T>
with Object
but I wanted to know if there is a better solution. 我可以用
Object
代替<T>
,但是我想知道是否有更好的解决方案。 The above method signature, obviously doesn't work :) 上面的方法签名,显然不起作用:)
SomeTypes
are created by the system and operated upon in the code. SomeTypes
由系统创建并在代码中进行操作。 I can't make any changes to their source. 我无法对其来源进行任何更改。
You are close to a generic method solution. 您已接近通用方法解决方案。 Define your generic type parameter with
<T>
, then use it without its own <>
in the return type and parameter type. 使用
<T>
定义您的通用类型参数,然后在返回类型和参数类型中使用不带自己的<>
的通用类型参数。
public <T> TreeMap<Integer, T> transformMap(Map<T, Double> myMap) {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.