繁体   English   中英

使用HashMap Value从TreeSet中删除对象

[英]Using HashMap Value to remove object from TreeSet

我有一个HashMap ,其中key是一个字符,value是一些用户定义的对象。 我在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

}

}

比较类:

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;
}


}

输出:26 26

请帮忙。 如果对象是String or Integer, TreeSet.remove()可以正常工作。 但不适用于用户定义的对象。

用于创建TreeSetNew_Comparison比较器的compare方法永远不会返回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;
}

实现比较方法,就好像两个值相等,比较方法将失败。

public int compare(Trial n1, Trial n2) {
   return  n1.c.compareTo(n2.c);
}

比较者错了,试试这个

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

我将使用的一种方法是在没有实现比较器的情况下使用TreeSet的contains()方法。 这是一种方式,但如何做逻辑是你的选择。

if(root.set.contains(t)){
    root.set.remove(t); 
}  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM