对象的集合如何反应?

时间:2014-03-05 20:46:30

标签: java methods collections

我的程序包含一个对象,我想了解如果我不能使用这些方法,包含对象的集合如何帮助我?

我使用的代码:

ClassMain c = new ClassMain();
Map<String, ClassMain> s = new HashMap<>();
s.put("S", c);
Iterator it = s.keySet().iterator();

while(it.hasNext())
{
    Object key = it.next();
    System.out.println(key);
}

ClassMain:

public static void main(String[] args) {
}

public void print(){
    System.out.println("Printing");
}

3 个答案:

答案 0 :(得分:2)

Iterator是一种通用类型。但是你将它用作原始类型。所以你丢失了应该有的类型信息。

代码应为:

Iterator<String> it = s.keySet().iterator();

while (it.hasNext()) {
    String key = it.next();
    System.out.println(key);
}

或更简单:

for (String key : s.keySet()) {
    System.out.println(key);
}

答案 1 :(得分:0)

这是raw type,你不必使用它:

Iterator it = ... ;

keySet返回一个参数化的Set<K>,你可以在这里使用,所有返回另一种Collection的Collections方法都是如此:

Iterator<String> = s.keySet().iterator();

这将允许您使用next返回的对象作为您提供给地图的实际类型:

while(it.hasNext())
{
    String key = it.next();
    System.out.println(key);
}

答案 2 :(得分:0)

集合用于存储事物的集合。您可以像Map一样拉出对象:

ClassMain c = new ClassMain();
Map<String, ClassMain> s = new HashMap<String, ClassMain>();
s.put("S", c);

for (String key : s.keySet())
{
    ClassMain c = s.get(key);
    c.print();
}