Vishnu
Vishnu

Reputation: 565

Eliminate typecasting when extracting from Map

I have requirement where a Map is of the type HashMap<String, Object>. Value in the Map is of the type Object as the values are of different data types. Though using Object helps solve my problem, I have to typecast every time i try to get(key) from the HashMap.

Is there any library available that would help me do away with these frequent typecasting?

Thanks in advance!

Upvotes: 2

Views: 218

Answers (2)

Bohemian
Bohemian

Reputation: 424983

You could hide the cast inside your own impl:

public class FlexiMap extends HashMap<String, Object> {
    public <T> T getType(String key) {
        return (T)get(key);
    }
}

Java can infer the type when you use it.

Boolean b = myMap.getType("foo"); // no cast

Upvotes: 2

Eran
Eran

Reputation: 393781

No. If you have to store the values of your Map using Object type, you can't avoid casting.

You should consider if it makes sense for all the possible types of values that can be in your Map to implement some common interface or have a common base class. This would allow you to replace Object with a more specific type, and reduce (and perhaps even eliminate) the need of casting.

Upvotes: 3

Related Questions