首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Enumeration<Object> eo1 = p2.propertyName()中,为什么需要将p2.propertyName()转换为Enumeration<Object>?

在Enumeration<Object> eo1 = p2.propertyName()中,为什么需要将p2.propertyName()转换为Enumeration<Object>?
EN

Stack Overflow用户
提问于 2016-03-02 19:01:41
回答 1查看 35关注 0票数 0

我正在尝试学习Java类的属性。我想打印出属性的关键字列表。但是,IDE显示以下错误:

代码语言:javascript
复制
Enumeration<Object> eo1 = p2.propertyNames();
//error, cast...propertyNames(...) to Enumeration

我做了以下更改:

代码语言:javascript
复制
Enumeration<Object> eo1 = (Enumeration<Object>) p2.propertyNames();

一切都很好。然而,我只是想知道为什么我需要将propertyNames()转换为Enumeration<Object>。我知道p2.propertyNames()返回一个枚举对象,但是它的语法对于像我这样的初学者来说是非常混乱的。

代码语言:javascript
复制
Properties p1 = new Properties();

try (OutputStream os1 = new FileOutputStream("random.txt")){
    p1.setProperty("1", "one");
    p1.setProperty("2", "two");
    p1.setProperty("3", "three");
    p1.store(os1, "comment");
} catch(IOException e){
    e.printStackTrace();
}

Properties p2 = new Properties();
try (InputStream is1 = new FileInputStream("random.txt")){
    p2.load(is1);
    System.out.println(p2.getProperty("2"));
} catch (IOException e){
    e.printStackTrace();
}

Enumeration<Object> eo1 = p2.propertyNames();
while (eo1.hasMoreElements()){
    System.out.println(eo1.nextElement());
}
EN

回答 1

Stack Overflow用户

发布于 2016-03-02 19:09:46

检查propertyNames()的返回类型。它不是枚举。它的public Enumeration<?> propertyNames()。两者都是不同的。阅读有关generics的更多信息

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35745329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档