HashSet的迭代器出现问题 [英] problem with a HashSet's Iterator
问题描述
我试图查看HashSet是否将是我下一个项目的解决方案,所以我正在做一些非常简单的测试来检查功能.我有一个简单的类 Klant
:
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;
}
}
和具有直通组成的类使用 HashSet
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.);
}
}
}
问题出在方法 toon()
基本上,即使我指定迭代器将包含Klant对象< Klant>
本地 k
对象不向我提供 Klant
中定义的 getKlantNummer()
方法 k
对象仍然是一个 Object
实例,甚至通过以下方式对其进行强制转换:
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.
有什么建议吗?
推荐答案
在类定义中,您拥有
public class MySet<Klant> {
该 Klant
被解释为您的类的类型参数(就像 E
用于 Collection
或 K
和 V
用于 Map
.当您随后在 MySet
中使用它时,它会覆盖您的实际类 Klant
,并且由于它的擦除是 Object
(如您未指定上限)您的 MySet
类中类型为 Klant
的变量将仅查看 Object
的方法.删除type参数并使用
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 {
你应该很好.
这篇关于HashSet的迭代器出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!