problem with a HashSet's Iterator
I'm trying to see if HashSet would be the solution for my next project so i'm doing some very easy test to check functionalities.
I have a simple class Klant
:
public class Klant {
private int klantNummer;
public Klant(int nummer) {
this.klantNummer = nummer;
}
public int getKlantNummer() {
return this.klantNummer;
}
}
and a class with through composition uses a HashSet
public class MySet<Klant> {
private Collection<Klant> mySet = null;
public MySet() {
mySet=new HashSet<Klant>();
}
public void add(Klant elem) {
mySet.add(elem);
}
public void toon() {
Iterator<Klant> i = mySet.iterator();
while(i.hasNext()) {
Klant k = i.next();
System.out.println(k.);
}开发者_运维知识库
}
}
The problem is in the method toon()
Basically even though i specify that the Iterator will contain Klant objects <Klant>
The local k
object does not provide me with the getKlantNummer()
mthod defined in Klant
The k
object its still an Object
instance, and even by casting it with:
Object k = (Klant)i.next();
it won't work. Down-casting is dangerous, but as far as i remember it is not prohibited.
Any advice?
In your class definition, you have
public class MySet<Klant> {
That Klant
is being interpreted as a type parameter for your class (just like E
is for Collection
or K
and V
are for Map
). It is overriding your actual class Klant
when you subsequently use it within MySet
, and since its erasure is Object
(as you specified no upper bound) a variable of type Klant
within your MySet
class will only see Object
's methods. Remove the type parameter and use
public class MySet {
and you should be good.
精彩评论