?
Solved

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

Posted on 2010-08-23
21
Medium Priority
?
1,201 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 86

Accepted Solution

by:
CEHJ earned 1000 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 1000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month14 days, 13 hours left to enroll

771 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