TreeSet会移除掉具有相同比较器值的不同项。我不想让它们被移除。 有没有什么方法可以控制这个行为?或者使用另一个容器类?
补充说明: 好的,看来我不能使用Set。 我需要插入排序功能,出于性能考虑。 List能够实现这个吗?感谢所有人。
TreeSet会移除掉具有相同比较器值的不同项。我不想让它们被移除。 有没有什么方法可以控制这个行为?或者使用另一个容器类?
补充说明: 好的,看来我不能使用Set。 我需要插入排序功能,出于性能考虑。 List能够实现这个吗?感谢所有人。
根据定义,集合中不能有重复项。
因此,您需要使用列表、数组或类似的数据结构。
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
使用:
public int compare(Integer o1, Integer o2) {
return o1 < o2 ? -1: 1;
}
class SortedArrayList extends ArrayList<String> {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void add(int index, String element) {
super.add(index, element);
Collections.sort(this);
}
@Override
public boolean add(String element) {
boolean returnValue = super.add(element);
Collections.sort(this);
return returnValue;
}
@Override
public boolean addAll(Collection<? extends String> c) {
boolean returnValue = super.addAll(c);
Collections.sort(this);
return returnValue;
}
@Override
public boolean addAll(int index, Collection<? extends String> c) {
boolean returnValue = super.addAll(index, c);
Collections.sort(this);
return returnValue;
}
@Override
public String set(int index, String element) {
String returnValue = super.set(index, element);
Collections.sort(this);
return returnValue;
}
}
我希望我已经包含了所有需要排序的功能。(不需要覆盖删除)
==
时,您可以返回0,否则比较System.identityHashCode()
或仅为具有相同内容但不是同一对象的对象返回任意1
。 - Peter LawreySystem.identityHashCode
不是唯一的。因此,您仍需要一个决胜者(可能使用WeakReference
)。 - Tom Hawtin - tackline