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> {
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 对象
本地 k
对象没有为我提供 Klant
中定义的 getKlantNummer()
方法 k
对象仍然是一个 Object
实例,即使通过使用以下方式进行转换:
Object k = (Klant)i.next();
它也不起作用。 向下转换是危险的,但据我记得它并没有被禁止。
有什么建议吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在类定义中,
Klant
被解释为类的类型参数(就像E
代表Collection
或K
和V
用于地图
)。当您随后在MySet
中使用它时,它会覆盖您的实际类Klant
,并且因为它的擦除是Object
(因为您没有指定上限)MySet
类中Klant
类型的变量只能看到Object
的方法。删除类型参数并使用,你应该会很好。
In your class definition, you have
That
Klant
is being interpreted as a type parameter for your class (just likeE
is forCollection
orK
andV
are forMap
). It is overriding your actual classKlant
when you subsequently use it withinMySet
, and since its erasure isObject
(as you specified no upper bound) a variable of typeKlant
within yourMySet
class will only seeObject
's methods. Remove the type parameter and useand you should be good.