NeplatnyUdaj
NeplatnyUdaj

Reputation: 6242

How to iterate over generic Map

I want to create a clone() method for the generic class containing generic map, but I'm stuck on iterating over the entryset of the map. Here's the important part:

private Map<Object, ObjectWrapper<E>> map = new ConcurrentHashMap<Object, ObjectWrapper<E>>();
for (Map.Entry<Object, ObjectWrapper<E>> entry: map.entrySet()){
    ....
}

The compiler error is this:

[ERROR] found   : java.util.Map.Entry<java.lang.Object,abc.ObjectWrapper<E>>
[ERROR] required: java.util.Map.Entry<java.lang.Object,abc.ObjectWrapper<E>>

Looks the same to me:)

I'm able to do the stuff by iterating over the keys and retrieve values inside the loop, but I'll get into trouble with Sonar. I've tried casting the result of map.entrySet() to a lot of things(like Set<? extends<Map.Entry<Object, ObjectWrapper<E>>>) as suggested in similar topics, but with no results:(

EDIT: The problem was using the generic parameter in both the class and the method. For future reference, here's the SSCE(not working):

public class Test<E> {
private Map<Object, ObjectWrapper<E>> map = new ConcurrentHashMap<Object, ObjectWrapper<E>>();

public <E> Test<E> test(){
    for (Map.Entry<Object, ObjectWrapper<E>> entry: map.entrySet()){
    }
    return null;
}

private static class ObjectWrapper<T>{
}

}

Upvotes: 1

Views: 2123

Answers (1)

keelar
keelar

Reputation: 6026

The following code built up from your partial code works for me in java version 1.6.0_24 without any errors

import java.lang.*;
import java.util.*;
import java.util.concurrent.*;

public class CMap<E>{
  public CMap() {

  }
  public void test() {
    Map<Object, List<E>> map = new ConcurrentHashMap<Object, List<E>>();
    for (Map.Entry<Object, List<E>> entry: map.entrySet()){

    }
  }

  public static void main(String[] args) {
    CMap<Integer> cMap = new CMap<Integer>();
    cMap.test();
  }
}

its compiling and execution log:

$ javac CMap.java
$ java CMap

Upvotes: 1

Related Questions