[英]Using HashMap Value to remove object from TreeSet
我有一个HashMap
,其中key是一个字符,value是一些用户定义的对象。 我在TreeSet
添加相同的对象。 HashMap
和TreeSet
中的条目数相等。
后来我想使用用户提供的字符输入从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()
可以正常工作。 但不适用于用户定义的对象。
用于创建TreeSet
的New_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.