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
That
Klantis being interpreted as a type parameter for your class (just likeEis forCollectionorKandVare forMap). It is overriding your actual classKlantwhen you subsequently use it withinMySet, and since its erasure isObject(as you specified no upper bound) a variable of typeKlantwithin yourMySetclass will only seeObject‘s methods. Remove the type parameter and useand you should be good.