How to use a custom class as a type variable for an Iterator?
I have the following code using generics:
Set membersKeySet = membersList.keySet(); Iterator<DoubleKey> membersItr = membersKeySet.iterator(); while(membersItr.hasNext()){ DoubleKey<Integer, Integer> dk = membersItr.next(); }
Eclipse tells me that "Set is a raw type. References to generic type <E> should be parametrized". DoubleKey is also a Generic class. What I understand is that the .iterator() method doesn't assure that the DoubleKey Class has been passed with the same parameter types. I tried typecasting but it doesn't work. How can I pull this off? Thanks!
P.S. I'开发者_开发问答m still n00b inusing Generics.
If the objects stored in the set are instances of DoubleKey<Integer, Integer>
, then the code should look like this :
Set<DoubleKey<Integer, Integer>> membersKeySet = membersList.keySet();
Iterator<DoubleKey<Integer, Integer>> membersItr = membersKeySet.iterator();
while(membersItr.hasNext()){
DoubleKey<Integer, Integer> dk = membersItr.next();
}
You should define type of the keyset.
Set<DoubleKey> membersKeySet = membersList.keySet();
Could you please provide memberList
definition to provide the full picture?
Well depending on what membersList
is, I'd expect this to be the solution:
Set<DoubleKey> membersKeySet = membersList.keySet();
If membersList
is also declared using a raw type, it becomes trickier... but we'll cross that bridge when you've checked whether that's all you need :)
From the code you give, it looks like membersList is actually a map of some sort. So, in order to get the compile time type safety of generics, membersList should be defined appropriately, something like
Map<DoubleKey, Object> membersList = new HashMap<DoubleKey, Object>();
Set<DoubleKey> membersKeySet = membersList.keySet();
With that, your iterator should work as you have it.
Normally you'd use the compact for-loop notation:
while(DoubleKey<Integer, Integer> dk: membersList.keySet()) { }
And if you are using DoubleKey<Integer, Integer>
all over the place, consider making it a class all on its own:
class IIKey extends DoubleKey<Integer, Integer> {}
精彩评论