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) {
Trial root = new Trial('0', 0);
int i;
for(i = 0; i < 26; i++)
{
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());
Trial t = root.map.get('c');
if(t == null)
return;
root.set.remove(t);
System.out.println(root.set.size());
}
}
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.
source
share