使用HashMap Value从TreeSet中删除对象

Cur*_*ous 4 java hashmap treeset

我有一个HashMapwhere键是一个字符,值是一些用户定义的对象.我正在添加相同的对象TreeSet.条目数HashMapTreeSet相等.

后来我想从HashMap使用用户提供的字符输入中检索一个对象.从中检索对象时HashMap,我想从中删除相同的对象TreeSet.但是,TreeSet.remove()不识别对象.

import java.util.TreeSet;
import java.util.HashMap;

public class Trial {

char c;
int count;  
HashMap<Character, Trial> map;
TreeSet <Trial> set;

public Trial(char c, int count)
{
    this.c = c;
    this.count = count;
    map = new HashMap<Character, Trial>();
    set = new TreeSet<Trial>(new New_Comparison());     
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Trial root = new Trial('0', 0);
    int i;
    for(i = 0; i < 26; i++) //add all characters a-z with count 0-25 resp. in root
    {
        char ch = (char)('a' + i);
        Trial t = new Trial(ch, i);
        root.map.put(ch, t);
        root.set.add(t);            
    }

    System.out.println(root.set.size()); //size = 26
    Trial t = root.map.get('c');
    if(t == null)
        return;
    root.set.remove(t);     
    System.out.println(root.set.size());        //size remains the same, expecting 25

}

}
Run Code Online (Sandbox Code Playgroud)

比较类:

import java.util.Comparator;

public class New_Comparison implements Comparator <Trial>{

public int compare(Trial n1, Trial n2) {
    if(n1.c <= n2.c)
        return 1;
    return -1;
}


}
Run Code Online (Sandbox Code Playgroud)

输出:26 26

请帮忙.如果对象要么String or Integer, TreeSet.remove()完美无缺.但不适用于用户定义的对象.

Era*_*ran 9

用于创建never compareNew_Comparison比较器的方法TreeSet返回0,因此就TreeSet所涉及的情况而言,没有两个Trial元素是相等的.

这就是为什么set.remove(t)不删除任何东西.

将其更改为:

public int compare(Trial n1, Trial n2) {
    if(n1.c < n2.c)
        return 1;
    else if (n1.c > n2.c)
        return -1;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)