保持TreeSet排序为对象更改值 [英] maintaining TreeSet sort as object changes value

查看:171
本文介绍了保持TreeSet排序为对象更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,使用Comparable<>定义一个自然排序顺序。
这些都存储在TreeSets中。

I've got a object that defines a 'natural sort order' using Comparable<>. These are being stored in TreeSets.

除了删除和重新添加对象之外,还有另一种方法来更新排序定义排序顺序是否更新?

Other than removing and re-adding the object, is there another way to update the sort when the members that are used to define the sort order are updated?

推荐答案

正如其他人所说,没有内置的方法。但你可以总是子类化TreeSet,用你的构造函数选择,并添加所需的功能:

As others have noted, there is no in-built way. But you can always subclass that TreeSet, with your constructor(s) of choice, and add in the required functionality:

public class UpdateableTreeSet<T extends Updateable> extends TreeSet<T> {

    // definition of updateable
    interface Updateable{ void update(Object value); }

    // constructors here
    ...

    // 'update' method; returns false if removal fails or duplicate after update
    public boolean update(T e, Object value) {
       if (remove(e)) {
           e.update(value);
           return add(e);
       } else { 
           return false;
       }
    }
}

必须调用((UpdateableTreeSet)mySet).update(anElement,aValue)来更新排序值和排序本身。这需要您在数据对象中实现额外的 update()方法。

From then on, you will have to call ((UpdateableTreeSet)mySet).update(anElement, aValue) to update the sorting value and the sorting itself. This does require you to implement an additional update() method in your data object.

这篇关于保持TreeSet排序为对象更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆