为什么当我向 TreeSet 推入三个对象时,它只能容纳一个对象?
我想将一些对象推入 TreeSet(在 BigHeap 类中),但我遇到了问题:
这是我的主类:
# --------- Print 3 -----------
Logger.info("items.size() = " + items.size());
for (Item item : items) {
Long score = item.getScoreByQueryItems(queryItems);
Long itemId = item.id;
ItemCacheNode node = new ItemCacheNode(itemId,score);
bigHeap.push(node); <----- here is the push action ---------
# --------------Print three times------------
Logger.info("node.itemId = " + node.getItemId());
}
# ---------------Print 1----------
Logger.info("bigHeap.getTreeSet().size() = " + bigHeap.getTreeSet().size());
这是我的 BigHeap.java:
public class BigHeap<T> {
private TreeSet<T> treeSet;
public BigHeap(Comparator<T> comparator){
this.treeSet = new TreeSet<T>(comparator);
}
public void push(T o){
treeSet.add(o);
}
public TreeSet<T> getTreeSet(){
return this.treeSet;
}
}
问题是,为什么 bigHeap 推入三次(不同的对象)但只保留一个毕竟是对象。
I want to push some objects into a TreeSet(inside BigHeap class) but i got problem :
here is my Main class:
# --------- Print 3 -----------
Logger.info("items.size() = " + items.size());
for (Item item : items) {
Long score = item.getScoreByQueryItems(queryItems);
Long itemId = item.id;
ItemCacheNode node = new ItemCacheNode(itemId,score);
bigHeap.push(node); <----- here is the push action ---------
# --------------Print three times------------
Logger.info("node.itemId = " + node.getItemId());
}
# ---------------Print 1----------
Logger.info("bigHeap.getTreeSet().size() = " + bigHeap.getTreeSet().size());
And here's my BigHeap.java:
public class BigHeap<T> {
private TreeSet<T> treeSet;
public BigHeap(Comparator<T> comparator){
this.treeSet = new TreeSet<T>(comparator);
}
public void push(T o){
treeSet.add(o);
}
public TreeSet<T> getTreeSet(){
return this.treeSet;
}
}
The problem is , why the bigHeap push three times(different objects) but only hold one object after all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能是由于
Set
不允许元素重复造成的。您正在将
ItemCacheNode
类型的对象推送到名为 bigHeap 的set
ADT 中。现在,当将新对象添加到集合中时,按照错误的比较器会覆盖
TreeSet
原生的听起来 equals 方法,当且仅当未使用Set
接口正确实现 Treeset。根据上述文档,您的定义,
private TreeSet; treeSet = new TreeSet(comparator);
忽略了接口的使用,因此,通过不遵守
Set 的非重复功能的一般思想,显示了此错误的功能。代码>.
This would be something that could be attributed to the reason that
Set
doesn't allow for duplication of elements.You are pushing objects of type
ItemCacheNode
into aset
ADT named bigHeap. Now, when a new object is added to the set, as per the docs,An erroneous comparator would override the otherwise sounds equals method native to a
TreeSet
iff the Treeset is not correctly implemented using theSet
interface. As per the aforementioned docs,Your definition,
private TreeSet<T> treeSet = new TreeSet<T>(comparator);
ignores utilization of the interface and as a result, showed this erroneous functionality, by not complying with the general idea of non-duplication functionality of a
Set
.