有关java中TreeSet的问题

来源:百度知道 编辑:UC知道 时间:2024/05/31 16:47:34
public class Memory {
private TreeSet<Partion_structure> unused_partion_list=new TreeSet<Partion_structure>(new Unused_partion_comparator());
boolean malloc (String s){ Iterator<Partion_structure>unused_iterator=unused_partion_list.iterator();
while(unused_iterator.hasNext()){
Partion_structure temp= unused_iterator.next();
if( unused_partion_list.contains(temp)){
int xx;
}
}

下面是比较器的定义:
import java.util.Comparator;

public int compare(Object o1, Object o2) {
if(o1 instanceof Partion_structure && o2 instanceof Partion_structure)
{
Partion_structure po1=(Partion_structure)o1;
Partion_structure po2=(Partion_structure)o2;
if(po1.size<po2.size)
return -1;
if(po1.size>po2.size)
return 1;
if(po1.size

经研究TreeSet源代码发现,它最终是调用调用Comparator.compare()来遍历TreeSet中的元素,并与你的这个temp比较,如果有一个元素比较时返回0,则contains(temp)返回true。

unused_partion_list.contains(temp)返回结果分析:
从你的Comparator逻辑来看,只有当unused_partion_list中存在某个元素,其size和start属性均与temp的对应属性相等时,这个方法才有可能返回true,否则将始终返回false。

你应该让Partion_structure实现comparable接口,或者实现equals和hashcode方法

我想知道你的Partion_structure 的定义