简体   繁体   English

如何为参数列表和/或返回类型中的“任何映射条目”值创建通用方法签名?

[英]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.

相关问题 如何实现具有通用返回类型和通用参数的通用方法? - How can I implement generic method which has generic return type and generic parameter? 如何使方法通用以返回任何类型的列表 - How to make the method generic to return a List of any type 如何让 Java 方法返回任何类型的通用列表? - How to have Java method return generic list of any type? 如何创建泛型方法以返回泛型类型 - How to create generic method to return generic type 包含带有通用Map.Entry的参数的方法 - Method that contains parameter with generic Map.Entry 在调用接受Class <T>并返回T的泛型方法时,如何返回某个类型的列表? - How can I return a list of a certain type when calling a generic method that accepts a Class<T> and returns a T? 如何从Java中的泛型列表中获取参数类型? - How can I get parameter Type from generic list in Java? 如何创建一个返回通用列表作为返回值的 GetRequest? (弹簧靴) - How can I create a GetRequest that returns a generic list as return value? (Spring Boot) 我们可以创建具有通用返回类型的方法吗,它如何评估在编译时返回哪种类型? - Can we create method with generic return type and how does this evaluate which type to return at compile time? 如何使方法的泛型返回类型取决于参数类型? - How to make the generic return type of a method dependend of the parameter type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM