0

I have a custom Map using where Device is an instance of my class named Device.

devices = new HashMap<String, Device>();

I tried several Iterators and for loops suggested at StackOverflow, but all of them seem to produce errors and I don't know why.

Example errors:

enter image description here

and

enter image description here

xorinzor
  • 6,140
  • 10
  • 40
  • 70

4 Answers4

3

Looks like the declaration of devices is incorrect. It should be:

Map<String, Device> devices;

Not the raw ("erased") type, Map. Modern compilers should give you warnings for using raw types. Take note of compiler warnings.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
0

Can you try this:

HashMap<String, Device> devices = new HashMap<String, Device>();

// do stuff to load devices

Device currentDevice;
for (String key : devices.keySet()) {

    currentDevice = devices.get(key);
    // do stuff with current device

}
Jiman
  • 185
  • 2
  • 13
0

In the first scenario, you just give

for(Map.Entry entry:devices.entrySet()){}

is only enough and you dont need to cast Map.Entry(String,Device) there. In the second scenario, when you get the value from entry, it returns Object value, so you need to cast to your particular instance.So you have to give

Device device=(Device) pairs.getValue()

MGPJ
  • 1,062
  • 1
  • 8
  • 15
0

There are 3 ways you can Iterate over a map 1)Iterating over entries using For-Each loop. 2)Iterating over keys or values using For-Each loop. 3) Iterating using Iterator. (for this you can iterate using Generics or without Generics)

    Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}
user1759484
  • 43
  • 3
  • 7