Solved

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

Posted on 2010-08-23
21
1,185 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

867 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now