为什么 2008 年的这个简单 Java 示例在我最新的 Eclipse/JDK 中失败了?
这是一个非常简单的 Java 示例,旨在打印所有系统环境变量:
http://www.devdaily.com/blog/post/java/java-how-to-print-system-env-environment-variables
代码似乎非常简单 - 它只是迭代环境变量一个映射,打印每个键和值,但是当我执行代码时,出现以下错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from element type Object to String
这里发生了什么?这个示例是垃圾还是我设置 Eclipse/JDK 的方式阻止了它的工作?
仅供参考,我在 Eclipse 更新版本上使用带有 JDK 1.6.0_24 x86 的 Windows XP。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
示例代码完全是错误的 - 它不会(并且永远无法)编译,并且 eclipse 应该在代码中显示这一点。
问题是
Map envMap
是原始类型,因此envMap.keySet()
也是原始类型,其元素无法隐式转换为String 在增强的 for 循环中。
解决方案:只需将 Map 定义更改为:
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, soenvMap.keySet()
is also a raw type and its elements cannot be implicitly converted toString
in the enhanced for loop.The solution: simply change the Map definition to:
因为这个例子是错误的。它应该包含该行
而不是
Because the example is wrong. It should contain the line
rather than