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

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

问题描述

我有一个使用 Comparable<> 定义自然排序顺序"的对象.这些都存储在 TreeSet 中.

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天全站免登陆