问题与HashSet的迭代器 [英] problem with a HashSet's Iterator

查看:225
本文介绍了问题与HashSet的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图看看HashSet是否会成为我下一个项目的解决方案,所以我正在做一些非常简单的测试来检查功能。
我有一个简单的类 Klant

  public class Klant {
private int klantNummer;

public Klant(int nummer){
this.klantNummer = nummer;
}

public int getKlantNummer(){
return this.klantNummer;






以及具有贯穿组合的类使用 HashSet

  public class MySet< Klant> {
私人收藏< 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。);
}
}
}

问题在于方法 toon()
基本上,即使我指定Iterator将包含Klant对象< Klant>
本地 k 对象不能为我提供 getKlantNummer()
方法> Klant
k 对象仍然是 Object 实例,甚至通过投射它:

 对象k =(Klant)i.next(); 

不起作用。
向下投射是危险的,但据我记忆它是不被禁止的。



有什么建议?



  public class MySet< Klant> =h2_lin>解决方案

; {

Klant 被解释为类的参数(就像 E 是用于集合 K V 用于 Map )。当您随后在 MySet 中使用它时,它重写实际的类 Klant ,并且由于其擦除操作是<$ c $在你的 MySet 中有一个类型 Klant 的变量c> Object c> class只会看到 Object 的方法。删除类型参数并使用

  public class MySet {

,你应该很好。


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.

这篇关于问题与HashSet的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆