Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an EnumMap in Spring 3.0

Tags:

spring

I've been trying to define an EnumMap in Spring using . I tried the following variations

<util:map map-class="java.util.EnumMap" key-type="xyz.EnumType">
<entry key="SOME_ENUM_TYPE">
   <ref bean="someBean"/>
</entry>
</util:map>

I get the following error

Error creating bean with name 'util:map#1c599b0e': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.EnumMap]: No default constructor found; nested exception is java.lang.NoSuchMethodException: java.util.EnumMap.<init>()

The following definition is what I tried initially

<util:map map-class="java.util.EnumMap">
<entry key="SOME_ENUM_TYPE">
   <ref bean="someBean"/>
</entry>
</util:map>

and this gave me some error of not being able to assign the enumtype to String.

There are examples on the site to using a generic map, but I am trying to see whether I can use an EnumMap, since it's considered the most optimal for Enums. The answer might be very obvious, so my apologies if the question is stupid. This is probably due to my limited knowledge of Spring. Thanks

like image 750
Seagull Avatar asked Dec 20 '11 20:12

Seagull


People also ask

What is EnumMap and EnumSet?

EnumMap is a specialized implementation of the Map interface for the enumeration types. EnumSet is a specialized implementation of the Set interface for the enumeration types. EnumMap is internally represented as an array. EnumSet is internally represented as a BitVector.

Can we use enum as map key?

Using Enum as key makes it possible to do some extra performance optimization, like a quicker hash computation since all possible keys are known in advance.

Which is a restriction of an EnumMap?

An EnumMap uses the restriction that all keys of a map will be from the same enum to gain performance benefits: Enum maps are represented internally as arrays. This representation is extremely compact and efficient. In this case, the keys and values are stored in separate arrays and the values are ordinal-ordered.


1 Answers

I guess you cannot initialize EnumMap with <util:map>. However, EnumMap has a constructor that takes an existing Map, you can try to use it:

<bean class = "java.util.EnumMap">
    <constructor-arg>
        <util:map key-type="xyz.EnumType">
            <entry key="SOME_ENUM_TYPE"><ref bean="someBean"/></entry>
        </util:map> 
    </constructor-arg>
</bean>
like image 108
axtavt Avatar answered Oct 14 '22 17:10

axtavt