Why does this simple Java example from 2008 fail in my up-to-date Eclipse/JDK?
Here is a very simple example in Java intended to print out all of the system environment variables:
http://www.devdaily.com/blog/post/java/java-how-to-print-system-env-environment-variables
The code seems pretty simple - it just iterates over the environment variables as a mapping, printing each key and value, however when I execute the code I get the following error:
Exception in thread "main" java.lang.Error: Unresolved开发者_StackOverflow中文版 compilation problem:
Type mismatch: cannot convert from element type Object to String
What is going on here? Is the example garbage or have I set up my Eclipse / JDK in a manner which prevents this from working?
FYI, I'm using Windows XP with JDK 1.6.0_24 x86 on an update version of Eclipse.
The example code is simply wrong - it does not (and never could) compile and eclipse should show that in the code.
The problem is that Map envMap
is a raw type, so envMap.keySet()
is also a raw type and its elements cannot be implicitly converted to String
in the enhanced for loop.
The solution: simply change the Map definition to:
Map<String,String> envMap = System.getenv();
Because the example is wrong. It should contain the line
Map<String, String> envMap = System.getenv();
rather than
Map envMap = System.getenv();
精彩评论