PhD
PhD

Reputation: 11334

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. 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. I could replace <T> with Object but I wanted to know if there is a better solution. The above method signature, obviously doesn't work :)

SomeTypes are created by the system and operated upon in the code. I can't make any changes to their source.

Upvotes: 0

Views: 206

Answers (1)

rgettman
rgettman

Reputation: 178293

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.

public <T> TreeMap<Integer, T> transformMap(Map<T, Double> myMap) {...}

Upvotes: 3

Related Questions