Solved

Generic Arguments of type Enum -- Can't Call valueOf()

Posted on 2010-08-23
21
1,187 Views
Last Modified: 2012-05-10
In the code, the two lines where the method "valueOf()" is called on my generic parameters of type Enum are giving an error:

"The method valueOf(String) is undefined for the type class <capture#3 of ? extends Enum>"

But my generic argument is of type enum, so I don't understand this error.  

Ulitmately, my goal is to convert a string representation of a hashmap (whose keys are enums and whose values are arraylists of enums) into a proper hashmap of the correct enum types.  Since there are different possible enums that can be used as the keys and values, I need a generic solution to avoid recreating the same method over and over for all the types.  

I am also confused by the definition of the Enum type:

public abstract class Enum<E extends Enum<E>>

It appears that parameterizing it by itself would create an infinite regression.  

Thanks,
Jonah
protected static <K extends Enum<?>, V extends Enum<?>> HashMap<K,ArrayList<V>> getHmap(String s, K keyType, V valType) {
        HashMap<K, ArrayList<V>> ret = new HashMap<K, ArrayList<V>>();
        HashMap<String, String[]> strHashmap = getStringHashmap(s);
        Iterator<String> iter = strHashmap.keySet().iterator();
        while (iter.hasNext()) {
            String oldKey = iter.next();
            String[] oldVals = strHashmap.get(oldKey);
            K newKey = keyType.getClass().valueOf(oldKey);
            ArrayList<V> newVals = new ArrayList<V>(oldVals.length);
	        for(int i=0; i<oldVals.length; i++) {
	            newVals.add(valType.getClass().valueOf( oldVals[i]));
	        }
	        ret.put(newKey, newVals);
        }
        return ret;

Open in new window

0
Comment
Question by:Jonah11
  • 9
  • 7
  • 5
21 Comments
 
LVL 92

Expert Comment

by:objects
ID: 33508299
0
 
LVL 7

Author Comment

by:Jonah11
ID: 33508323
What about usage like this:

http://www.java2s.com/Code/JavaAPI/java.lang/EnumvalueOfStringv.htm

Also, even if I change the code to:
K newKey = Enum.valueOf(keyType.getClass(),oldKey);

it still does not work.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 33508430
Try
            K newKey = K.valueOf(keyType.getDeclaringClass(), oldKey);
            ArrayList<V> newVals = new ArrayList<V>(oldVals.length);

            for (int i = 0; i < oldVals.length; i++) {
                newVals.add(valType.valueOf(valType.getDeclaringClass(), oldVals[i]));
            }

Open in new window

0
Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

 
LVL 86

Accepted Solution

by:
CEHJ earned 250 total points
ID: 33508451
That needs the following method prototype (adjusted to return the more generic and flexible Map as opposed to HashMap)
protected static <K extends Enum<K>, V extends Enum<V>> Map<K, List<V>> getMap(
        String s, K keyType, V valType)

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 33508472
The whole method:
    protected static <K extends Enum<K>, V extends Enum<V>> Map<K, List<V>> getMap(
        String s, K keyType, V valType) {
        Map<K, List<V>> ret = null;

        HashMap<String, String[]> strHashmap = getStringHashmap(s);
        Iterator<String> iter = strHashmap.keySet().iterator();

        while (iter.hasNext()) {
            String oldKey = iter.next();
            String[] oldVals = strHashmap.get(oldKey);
            K newKey = K.valueOf(keyType.getDeclaringClass(), oldKey);
            List<V> newVals = new ArrayList<V>(oldVals.length);

            for (int i = 0; i < oldVals.length; i++) {
                newVals.add(valType.valueOf(valType.getDeclaringClass(), oldVals[i]));
            }

            ret.put(newKey, newVals);
        }

        return ret;
    }

Open in new window

0
 
LVL 7

Author Comment

by:Jonah11
ID: 33512610
CEHJ,

Thanks very much, that works.  I still don't completely understand why, however.  Can you answer a few more questions:

1.  Why does getDeclaringClass work but getClass does not?  
2.  Why does the syntax used in this example NOT work:
http://www.java2s.com/Code/JavaAPI/java.lang/EnumvalueOfStringv.htm
3.  Why did we need to use the syntax "<K extends Enum<K>", which is also used by the definition of the Enum class itself?  As I said, it seems to be self referential and thus confuses me.

Thanks again,
Jonah
0
 
LVL 92

Expert Comment

by:objects
ID: 33516340
Don't you love it when someone posts some code but cannot actually explain it :)
0
 
LVL 92

Expert Comment

by:objects
ID: 33516394
Will see if I can help you

> 1.  Why does getDeclaringClass work but getClass does not?  

The two aren't actually related, you need Enum.getDeclaringClass() to the the Enum class to call valueOf() as I mentioned in my earlier comment

http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html#getDeclaringClass()

> 2.  Why does the syntax used in this example NOT work:

thats a special case I think, will check that for you
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 33516418
1. Because the compiler needs to allow for the fact that the type might use a constant-specific class body (see API doc)
2. How would you use that?
3. That's the way Enum is defined
0
 
LVL 92

Expert Comment

by:objects
ID: 33516429
rotfl :D
0
 
LVL 7

Author Comment

by:Jonah11
ID: 33516471
objects, thanks for that explanation of 1.

CEHJ, regarding point 2, I was thinking, in analogy with the example in that link, that something like:

 K newKey = keyType.getClass().valueOf(oldKey);

might work, but it does not.

Regarding 3, I understand that is the definition, but the definition seems paradoxical to me.  That is, looking at the definition of Enum itself we have:

Class Enum<E extends Enum<E>>

which is a generic definition, but the objects allowed in the generics must extend Enum<E>, but what is the definition of Enum<E>?  Won't this give us an infinite regress?

0
 
LVL 92

Expert Comment

by:objects
ID: 33516504
>  K newKey = keyType.getClass().valueOf(oldKey);

thats calling valueOf() on the Class instance, not the enum.
0
 
LVL 7

Author Comment

by:Jonah11
ID: 33516608
objects, okay, bear with me.  The line from the example I linked is:

ap = Apple.valueOf("C");

where Apple is the enum class in question.  So I am still not seeing the difference.  Thanks.
0
 
LVL 92

Expert Comment

by:objects
ID: 33516661
>  K newKey = keyType.getClass().valueOf(oldKey);

getClass() returns a Class object (not an Enum object)
Class does not have a valueOf() method
0
 
LVL 7

Author Comment

by:Jonah11
ID: 33516761
ah ok, thanks.

finally, did you have an explanation of point 3, my question about the seeming infinite regress?
0
 
LVL 7

Author Comment

by:Jonah11
ID: 33516801
Also, I cannot seem to find any documentation on the valueOf(String) method used in that example -- all I see is this:

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Enum.html#valueOf%28java.lang.Class,%20java.lang.String%29

which is a different method.
0
 
LVL 92

Assisted Solution

by:objects
objects earned 250 total points
ID: 33516802
Its saying extenders of Enum can only pass themselves as E

some more reading on enums

http://madbean.com/2004/mb2004-3/
0
 
LVL 92

Expert Comment

by:objects
ID: 33516807
> Also, I cannot seem to find any documentation on the valueOf(String) method used in that example -- all I see is this:

thats a special case as I mentioned earlier
the compiler creates it, the link above discusses it I think
0
 
LVL 7

Author Comment

by:Jonah11
ID: 33517105
objects,

that is a great link, it answered all my questions.  thank you.  
0
 
LVL 92

Expert Comment

by:objects
ID: 33517134
Amazed how often people post code on this site that they are unable to actually explain
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 33518899
:-)
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
print map entry 34 69
fibonacci ten numbers 4 39
HashTable highest marks enumeration alternative 9 39
How do I remove an object from a 3 26
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
The viewer will learn how to implement Singleton Design Pattern in Java.
This video teaches viewers about errors in exception handling.

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question