【问题标题】:java TreeSet with custom comparator not working带有自定义比较器的 java TreeSet 不起作用
【发布时间】:2013-12-25 05:43:38
【问题描述】:

我正在尝试将自定义比较器与 TreeSet 一起使用。然而,似乎有些不对劲。无论我使用自定义等于还是比较器中的比较,我都会看到重复项。知道错误在哪里吗? 下面是代码:(请看cmets)

import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;

public class TreemapTest {

    public static void main(String[] args) {

        //Take an array of integers
        int list[] = { 1,2,3,4,2,4,2,5 };

        //Create a list of custom objects
        ArrayList<Element> elements = new ArrayList<Element>();

        //Populate the list with values from int array
        for (int v : list){
            elements.add(new Element(v));
        }

        /** Attempt to create a treeset from the arraylist */
        // Create the Treeset with custom comparator
        TreeSet<Element> nt = new TreeSet<Element>(new Comparator<Element>(){
            public int compare(Element a, Element b){
                System.out.println("Comparing "+ a.val + " and "+ b.val);
                if ( a.val == b.val ) 
                    return 0;
                if ( (a.val - b.val) > 0 )
                    return 1;
                return -1;
            }
        });

        // Add the elements into the treeset
        for (Element elem: elements ){
            nt.add(elem);
        }
        // Output shall not contain duplicates
        for (Element elem: elements ){
            System.out.print(":"+elem.val);
        }
    }
}

class Element {
    public int val;
    Element(int v){
        val = v;
    }
//  boolean equals(Element e){
//      return this.val == e.val;
//      
//  }
}

【问题讨论】:

    标签: java comparator treeset


    【解决方案1】:

    您再次打印elements 列表,将其更改为nt 集。

    // Output shall not contain duplicates
    for (Element elem: nt){
        System.out.print(":"+elem.val);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-27
      • 2011-12-26
      • 2015-06-21
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      相关资源
      最近更新 更多