problem with a HashSet's Iterator

橙三吉。 提交于 2019-12-24 09:39:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6235010/problem-with-a-hashsets-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!