-3

my program contains an object and i want to understand how a collections that contains objects is helping me if i can`t use the methods ?

My code that i used :

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 Answers3

2

Iterator is a generic type. But you use it as a raw type. So you lose the type information it should have.

The code should be:

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

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

Or simpler:

for (String key : s.keySet()) {
    System.out.println(key);
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

This is a raw type and you don't have to use it:

Iterator it = ... ;

keySet returns a parameterized Set<K> which you can use here, as do all of the Collections methods that return another kind of Collection:

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

This will let you use the objects returned by next as the actual type you've supplied to the Map:

while(it.hasNext())
{
    String key = it.next();
    System.out.println(key);
}
Community
  • 1
  • 1
Radiodef
  • 37,180
  • 14
  • 90
  • 125
0

Collections are used for, well storing collections of things. You can pull out the objects in a Map like so:

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();
}
Chris Dargis
  • 5,891
  • 4
  • 39
  • 63