Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / May 2007

Tip: Looking for answers? Try searching our database.

Passing enum and EnumMap to a method

Thread view: 
~kurt - 15 May 2007 05:43 GMT
Generics are really new to me, and catching on has been a bit confusing.
The Sun tutorial is like a man page - you gotta read it a few times and
I've been too impatient to do so.  I've actually been reading through
the java.util.EnumMap code to get a better grip on things.  Since all
my googling didn't turn up an example of how to pass enums (and EnumMaps),
I figured I'd post it here for others if they have the same question.
Some of the recent threads on this topic were very helpful to me, but
I still needed to put it all together.

If anyone sees anything stupid (or any suggestions for improvement,
please let me know).

import java.util.*;

public class TestEnumMap {

 enum ThreeD { X, Y, Z }

 public static void main(String[] args) {

   double dval;

   EnumMap<ThreeD, Double> xyz =
                     new EnumMap<ThreeD, Double>(ThreeD.class);

   xyz.put(ThreeD.X, 5.0);
   xyz.put(ThreeD.Y, 10.0);
   xyz.put(ThreeD.Z, 15.0);
   System.out.println("Not Passed");
   for (ThreeD i : ThreeD.values()) {
     dval = xyz.get(i);
     System.out.println("" + i + ":  " + dval);
   }

   printVals(xyz);
   printVals(ThreeD.class, xyz);
 }
 public static void printVals (EnumMap<ThreeD, Double> em) {
   System.out.println("Passed, but with just the EnumMap:");
   double dval;
   for (ThreeD i : ThreeD.values()) {
     dval = em.get(i);
     System.out.println("" + i + ":  " + dval);
   }
 }

 public static <K extends Enum<K>> void printVals(Class<K> keyType,
                                            EnumMap<ThreeD, Double> em) {
   double dval;
   K[] keyUniverse = keyType.getEnumConstants();
   System.out.println("Everything Passed");
   for (int i=0; i<keyUniverse.length; i++) {
     dval = em.get(keyUniverse[i]);
     System.out.println("" + keyUniverse[i] + ":  " + dval);
   }
 }
}

- Kurt
Tom Hawtin - 15 May 2007 06:11 GMT
>   public static <K extends Enum<K>> void printVals(Class<K> keyType,
>                                              EnumMap<ThreeD, Double> em) {
>     double dval;
>     K[] keyUniverse = keyType.getEnumConstants();

The question didn't jump out at me, but I'm guessing you are asking how
to get all the elements of an enum given an EnumMap with the enum as the
key type.

AFAIK, the only guaranteed way to obtain the 'keyClass' that I can see
is through serialisation - not pleasant.

All you really can do is pass the information through separately.
However, your method declaration can be tidied up a little:

private static <K extends Enum<K>> void printVals(
    Class<K> keyType, Map<K, ?> map
) {

Tom Hawtin
~kurt - 15 May 2007 16:07 GMT
> The question didn't jump out at me, but I'm guessing you are asking how
> to get all the elements of an enum given an EnumMap with the enum as the
> key type.

Yep - just experimenting - seeing how I might use an EnumMap in the future.

> private static <K extends Enum<K>> void printVals(
>      Class<K> keyType, Map<K, ?> map
> ) {

Thanks,

- Kurt
Tom Hawtin - 15 May 2007 16:40 GMT
> The question didn't jump out at me, but I'm guessing you are asking how
> to get all the elements of an enum given an EnumMap with the enum as the
> key type.
>
> AFAIK, the only guaranteed way to obtain the 'keyClass' that I can see
> is through serialisation - not pleasant.

Ah, it seems that you can extract the full set of elements for the enum,
so long as you have a non-empty key-set. Of course if you have an
example element you can getClass, find the enum class and then all the
elements yourself.

import java.util.*;

class EnumMapToAllKeys {
    public static void main(String [] args) {
        Map<Thread.State, String> map =
            new EnumMap<Thread.State, String>(Thread.State.class);
        map.put(Thread.State.BLOCKED, "block");
        map.put(Thread.State.TIMED_WAITING, "timed");
        print(map);
    }
    /**
     * @throws IllegalArgumentException if map is empty(!)
     */
    private static <K extends Enum<K>> void print(Map<K, ?> map) {
        EnumSet<K> all = EnumSet.copyOf(map.keySet());
        all.addAll(EnumSet.complementOf(all));
        for (K key : all) {
            System.out.println(key+" => "+map.get(key));
        }
    }
}

It would work properly if EnumSet.copyOf could extract the class
information from EnumMap.keySet. Perhaps an RFE (and patch) is in order
to add that sort of functionality across collections.

Tom Hawtin
Daniel Pitts - 16 May 2007 00:52 GMT
> > The question didn't jump out at me, but I'm guessing you are asking how
> > to get all the elements of an enum given an EnumMap with the enum as the
[quoted text clipped - 36 lines]
>
> Tom Hawtin

Actually, it would be nice if EnumMap added the method Class<K>
getKeyType() to the interface.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.