Sabtu, 24 Mei 2014

What is EnumMap in Java – Example Tutorial




What
is EnumMap in Java


EnumMap in Java is added on JDK  5
release along with other important features like 
Autoboxing, varargs and Generics.
EnumMap
is specialized Map implementation designed and optimized for
using Java Enum as key. Since enum
can represent a type (like class or interface)  in Java and it can also override equals() and hashCode() , It
c
an be used inside HashMap or any other
collection but using  
EnumMap
brings implementation specific benefits which is done for enum keys, In
short EnumMap is optimized Map implementation exclusively for enum keys . As
per javadoc Enum is implemented using Arrays and common operations result in
constant time. So if you are thinking of an high performance Map,
EnumMap
could be decent choice for enumeration data. We have already seen many
examples of Java enum in our article 10 Examples of enum in Java  and using Enum as thread-safe Singleton.
In
this Java tutorial we will see simple examples of using
EnumMap
in Java. On related note Difference
between EnumMap and HashMap
is also getting popular as one of advanced Java
collection interviews questions
and most of Java IDE like Eclipse and
Netbeans will also suggest to use EnumMap if you use Enum keys along with
HashMap as part of there code improvement suggestion.










Important
points of
EnumMap
in Java:


What is EnumMap in Java with ExampleHere is few important points to remember about EnumMap in Java
which is also useful while using
EnumMap in code to
avoid any compile time or logical errors :





1. All keys used in EnumMap must be  from same Enum
type
which is specified while creating
EnumMap in Java.
For example if you can not use different enum instances from two different
enum.





2. EnumMap is ordered collection and they
are maintained in the natural order of their keys( natural order of keys
means  the order on which enum constant
are declared inside enum type ). you can verify this while Iterating over an
EnumMap
in Java.





3. Iterators of EnumMap are fail-fast Iterator , much like
of
ConcurrentHashMap and
doesn't throw
ConcurrentModificationException and may
not show effect of any modification on
EnumMap during
Iteration process.





4. You can not insert null keys inside EnumMap in Java.  EnumMap doesn't
allow
null key and throw NullPointerException, at same
time null values are permitted.





5. EnumMap is not synchronized and it has to
be synchronized m
anually before
using it in a concurrent or multi-threaded environment. like synchronized Map
in Java  you can also make
EnumMap
synchronized by using Collections.synchronizedMap() method and
as per javadoc this should be done while creating
EnumMap
in java to avoid accidental non synchronized access.





6. EnumMap is likely give better performance
than
HashMap in Java. So prefer EnumMap if you are going to use enum keys.







How to use EnumMap in Java – EnumMap Example



In this section we will see How to
use
EnumMap in Java with simple examples like
creating EnumMap, putting objects into EnumMap, getting objects from
EnumMap,  finding size of EnumMap, Iterating
over EnumMap, printing EnumMap in console , checking if
EnumMap contains a
particular key and value or not etc. All of these operations are similar to
other Map implementation like HashMap
and doesn’t
require special knowledge but It’s good to remember all points specific to
EnumMap as discussed in previous section to avoid any error.








import java.util.EnumMap;

import java.util.Iterator;





/**

 * Java program to demonstrate How to use EnumMap in Java

 * If Key Object is Enum than it’s best to EnumMap to get better
performance.


 * Most of IDE like Netbeans and
Eclipse suggest you to use EnumMap instead of HashMap


 * or any other Map
implementation when key object is Enum.


 *


 * @author Javarevisited

 */




public class
EnumMapExample{

 

    public enum STATE{

        NEW, RUNNING, WAITING, FINISHED;

    }



    public static void
main(String args[]) {

     

        // Java EnumMap Example
1: creating EnumMap in java with key as enum type STATE


        EnumMap<STATE,
String> stateMap = new EnumMap<STATE,
String>(STATE.class);

     

        // Java EnumMap Example
2:


        //putting values
inside EnumMap in Java


        //we are inserting
Enum keys on different order than their natural order


        stateMap.put(STATE.RUNNING,
"Program is running");

        stateMap.put(STATE.WAITING,
"Program is waiting");

        stateMap.put(STATE.NEW, "Program has just created");

        stateMap.put(STATE.FINISHED,
"Program has finished");

     

        // Java EnumMap Example
3:


        //printing size of EnumMap
in java


        System.out.println("Size of EnumMap in java: " + stateMap.size());

     

        // Java EnumMap Example
5:


        //printing Java EnumMap
, should print EnumMap in natural order


        //of enum keys
(order on which they are declared)


        System.out.println("EnumMap: " + stateMap);

     

        // Java EnumMap Example
5:


        //retrieving value
from EnumMap in java


        System.out.println("EnumMap key : " + STATE.NEW +" value: "
+ stateMap.get(STATE.NEW));

     

        // Java EnumMap Example
6:


        //Iterating over
Java EnumMap


        Iterator<STATE> enumKeySet = stateMap.keySet().iterator();

        while(enumKeySet.hasNext()){

            STATE currentState = enumKeySet.next();

            System.out.println("key : "
+ currentState + " value : " +
stateMap.get(currentState));

        }

     

        //Java EnumMap Example
7: checking if EnumMap contains a particular key


        System.out.println("Does stateMap has :" + STATE.NEW + " : "


                     
      +  stateMap.containsKey(STATE.NEW));

     

        //Java EnumMap Example
8: checking if EnumMap contains a particular value


        System.out.println("Does stateMap has :" + STATE.NEW + " : "
+ stateMap.containsValue(null));



    }

 

}



Output:

Size of EnumMap in java: 4

EnumMap: {NEW=Program has just
created, RUNNING=Program is running, WAITING=Program is waiting,
FINISHED=Program has finished}



EnumMap key : NEW value: Program has just created

key : NEW value : Program has just created

key : RUNNING value : Program is running

key : WAITING value : Program is waiting

key : FINISHED value : Program has finished

Does stateMap has :NEW : true

Does stateMap has :NEW : false








In summary if you are using enum keys or can use enum keys prefer EnumMap over HashMap or any other
Map implementation because
EnumMap is specialized Map
implementation for enum and provides better performance than general map. In
this Java tutorial we have seen What is EnumMap in Java, important
points about EnumMap in Java and How to use EnumMap with some how to type of
examples.





Other Java collection tutorials from Javarevisited blog.



































Source:http://javarevisited.blogspot.com/2012/09/what-is-enummap-in-java-example-tutorial.html

Tidak ada komentar:

Posting Komentar