在 Java 中从 TreeSet 中查找并返回一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17806543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 15:03:39  来源:igfitidea点击:

Find and return an element from a TreeSet in Java

java

提问by Joarder Kamal

I have the following Node Class

我有以下节点类

Class Node {
    private int id;

    public int getId() {
        return this.id;
    }
}

and then create a TreeSet with the Nodes. Next I wanted to find and return a Node object based on id matching. However, every time the findNode() function is returning the next-to-next Node not the next one. I understand it is because of calling the iterator.next() twice. How can call it only once to check with the id value as well as return the object reference. I also tried with by creating a temporary Object reference but again it was the same result.

然后用节点创建一个 TreeSet。接下来我想根据 id 匹配查找并返回一个 Node 对象。但是,每次 findNode() 函数都返回下一个节点而不是下一个。我明白这是因为两次调用 iterator.next() 。如何仅调用一次以检查 id 值并返回对象引用。我也尝试过创建一个临时的 Object 引用,但结果还是一样。

Class NodeSet {
    Set<Node> set = new TreeSet<Node>();

    public Node findNode(int id) {  
        Iterator<Node> iterator = set.iterator();
        while(iterator.hasNext()) {
            if(iterator.next().getId() == id)               
                return iterator.next();
        }

        return null;                
    }
}

回答by Debasis

Edit: The solution proposed here is logarithmic(unlike the accepted answer) and hence is much faster when the number of nodes in a treeset is large.

编辑:这里提出的解决方案是对数的(与接受的答案不同),因此当树集中的节点数量很大时,速度要快得多。

There is no getmethod in the Setinterface which the class TreeSetimplements. Keeping in mind that there exists a complete ordering between the elements of a treeset, a three line hack is as follows:

在类TreeSet实现的Set接口中没有get方法。请记住,树集的元素之间存在完整的排序,三行 hack 如下:

Object search(TreeSet treeset, Object key) {
    Object ceil  = treeset.ceiling(key); // least elt >= key
    Object floor = treeset.floor(key);   // highest elt <= key
    return ceil == floor? ceil : null; 
}

回答by Reddy

Class NodeSet {
    Set<Node> set = new TreeSet<Node>();

    public Node findNode(int id) {  
        Iterator<Node> iterator = set.iterator();
        while(iterator.hasNext()) {
            Node node = iterator.next();
            if(node.getId() == id)             
                return node;
        }

        return null;                
    }
}

回答by Mik378

The issue happens here:

问题发生在这里:

        while(iterator.hasNext()) {
            if(iterator.next().getId() == id)               
                return iterator.next();
        }

You call twice iterator.nextin the same loop explaining the "next-to-next" issue.

iterator.next在同一个循环中调用两次来解释“next-to-next”问题。

Make a local variable to still reach the same element or better: use the for loop if you have jdk >= 5:

制作一个局部变量以仍然到达相同的元素或更好:如果您有 jdk >= 5,请使用 for 循环:

for(Node node: set) {
   if(node.getId() == id) 
     return node;
}

As @JB Nizet suggests in his comment above, a simple Mapalready implements your code logic by essence, and thus would better fit than a TreeSetand manual check.
More precisely, a TreeMapsorted on Nodes would be relevant. (since it sounds you need the order aspect)

正如@JB Nizet 在他上面的评论中所建议的那样,一个简单Map的本质上已经实现了您的代码逻辑,因此比TreeSet手动检查更适合。
更准确地说,TreeMapNodes 进行排序是相关的。(因为听起来你需要订单方面)