Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HashMap Value to remove object from TreeSet

I have a HashMap where key is a character and value is some user-defined object. I am adding same objects in the TreeSet. The number of entries in HashMap and TreeSet are equal.

Later on I want to retrieve a object from HashMap using user supplied character input. Upon retrieving object from HashMap, I want to delete the same object from the TreeSet. However, the TreeSet.remove() doesn't 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 is either String or Integer, TreeSet.remove() works perfectly. But doesn't work for user-defined objects.

like image 344
Curious Avatar asked Jan 10 '23 07:01

Curious


1 Answers

The compare method of the New_Comparison comparator you use to create the TreeSet never returns 0, so it means that, as far as the TreeSet is concerned, no two Trial elements are equal.

That's why set.remove(t) doesn't remove anything.

Change it to :

public int compare(Trial n1, Trial n2) {
    if(n1.c < n2.c)
        return 1;
    else if (n1.c > n2.c)
        return -1;
    return 0;
}
like image 77
Eran Avatar answered Jan 22 '23 00:01

Eran