Using a HashMap Value to Remove an Object from a TreeSet

I have HashMapwhere the key is a symbol and the value is a user-defined object. I add the same objects to TreeSet. The number of entries in HashMapand TreeSetequal.

Later, I want to get the object from HashMapusing user-entered character input. After extracting the object from, HashMapI want to delete the same object from TreeSet. However, it TreeSet.remove()does not identify the object.

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

}

}

Comparator Class:

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


}

Output: 26 26

Please, help. If the object either String or Integer, TreeSet.remove()works fine. But does not work for custom objects.

+4
source share
4 answers

compare New_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;
}
+9

, .

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

The comparator is wrong, try

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

One approach that I would use, without implementing a comparator, contains () the TreeSet method. This is one way, but how to make logic is your choice.

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

All Articles