且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SortedSet的有限

更新时间:2022-10-15 16:29:12

通过标准的API,你必须自己做,即延长有序set类之一,你想要的逻辑添加到添加()的addAll()方法。应该不会太难。

顺便说一下,我不完全理解你的例子:

  t1.add(9);
// [1,2,3]

不应该设定包含 [1,2,9] 后来呢?

修改的:我想现在我明白了:你想只保留被添加到组,最小的3个元素吧

编辑2 的:示例实现(不优化)可能是这样的:

 类LimitedSortedSet< E>扩展TreeSet中< E> {  私人诠释MAXSIZE;  LimitedSortedSet(INT MAXSIZE){
    this.maxSize = MAXSIZE;
  }  @覆盖
  公共布尔的addAll(收集和LT ;?扩展E> c){
    布尔加入= super.addAll(三);
    如果(大小()> MAXSIZE){
      ËfirstToRemove =(E)的toArray()[MAXSIZE];
      的removeAll(tailSet(firstToRemove));
    }
    增加收益;
  }  @覆盖
  公共布尔加(E O){
    布尔补充= super.add(O);
    如果(大小()> MAXSIZE){
      ËfirstToRemove =(E)的toArray()[MAXSIZE];
      的removeAll(tailSet(firstToRemove));
    }
    增加收益;
  }
}


需要注意的是 tailSet()返回子集包括参数(如果设置)。这意味着,如果你不能计算出一个较高值(并不需要在设定的),你就必须重新进行添加的元素。这是在code以上完成。击>


如果你可以计算下一个值,例如如果你有一个整数集,做一些 tailSet(是以lastElement + 1)将足以和你不必重新进行添加的最后一个元素。
罢工>


另外,您可以在自己设定迭代并删除您想保留后面的最后所有元素。
罢工>


另一种选择,虽然这可能是更多的工作,将插入元件前检查尺寸,并相应地除去。
罢工>

更新的:作为msandiford正确地指出,应删除的第一个元素是一个索引 MAXSIZE 。因此,有没有必要重新进行添加(重新添加?)最后通缉的元素。

重要提示:
由于@DieterDP正确地指出,实现上述违反收藏#的add() API合约中规定,如果一个集合拒绝添加元素为其他任何原因不是它是是重复的错误时抛出的必须的异常。

在上面的元件首先加入,但可能会被再次除去由于尺寸限制或其他元素可能会被删除,因此,这违反了合同的示例

要解决这个问题,你可能需要修改添加()的addAll()来扔在这种情况下的例外(或者在为了使它们无法使用任何情况下),并提供alterante方法来添加不违反任何现有的API的合同内容。

在任何情况下,上面的例子中的应小心的,因为使用它与code,它是不知道的侵犯可能导致不必要的和难以调试的错误使用。

i'm looking for an implementation of SortedSet with a limited number of elements. So if there are more elements added then the specified Maximum the comparator decides if to add the item and remove the last one from the Set.

SortedSet<Integer> t1 = new LimitedSet<Integer>(3);
t1.add(5);
t1.add(3);
t1.add(1);
// [1,3,5]
t1.add(2);
// [1,2,3]
t1.add(9);
// [1,2,3]
t1.add(0);
// [0,1,2]

Is there an elegant way in the standard API to accomplish this?

I've wrote a JUnit Test for checking implementations:

@Test
public void testLimitedSortedSet() {
final LimitedSortedSet<Integer> t1 = new LimitedSortedSet<Integer>(3);
t1.add(5);
t1.add(3);
t1.add(1);
System.out.println(t1);
// [1,3,5]
t1.add(2);
System.out.println(t1);
// [1,2,3]
t1.add(9);
System.out.println(t1);
// [1,2,3]
t1.add(0);
System.out.println(t1);
// [0,1,2]
Assert.assertTrue(3 == t1.size());
Assert.assertEquals(Integer.valueOf(0), t1.first());
}

With the standard API you'd have to do it yourself, i.e. extend one of the sorted set classes and add the logic you want to the add() and addAll() methods. Shouldn't be too hard.

Btw, I don't fully understand your example:

t1.add(9);
// [1,2,3]

Shouldn't the set contain [1,2,9] afterwards?

Edit: I think now I understand: you want to only keep the smallest 3 elements that were added to the set, right?

Edit 2: An example implementation (not optimised) could look like this:

class LimitedSortedSet<E> extends TreeSet<E> {

  private int maxSize;

  LimitedSortedSet( int maxSize ) {
    this.maxSize = maxSize;
  }

  @Override
  public boolean addAll( Collection<? extends E> c ) {
    boolean added = super.addAll( c );        
    if( size() > maxSize ) {
      E firstToRemove = (E)toArray( )[maxSize];
      removeAll( tailSet( firstToRemove ) );
    }   
    return added;
  }

  @Override
  public boolean add( E o ) {    
    boolean added =  super.add( o );
    if( size() > maxSize ) {
      E firstToRemove = (E)toArray( )[maxSize];
      removeAll( tailSet( firstToRemove ) );
    }
    return added;
  }
}

Note that tailSet() returns the subset including the parameter (if in the set). This means that if you can't calculate the next higher value (doesn't need to be in the set) you'll have to readd that element. This is done in the code above.

If you can calculate the next value, e.g. if you have a set of integers, doing something tailSet( lastElement + 1 ) would be sufficient and you'd not have to readd the last element.

Alternatively you can iterate over the set yourself and remove all elements that follow the last you want to keep.

Another alternative, although that might be more work, would be to check the size before inserting an element and remove accordingly.

Update: as msandiford correctly pointed out, the first element that should be removed is the one at index maxSize. Thus there's no need to readd (re-add?) the last wanted element.

Important note: As @DieterDP correctly pointed out, the implementation above violates the Collection#add() api contract which states that if a collection refuses to add an element for any reason other than it being a duplicate an excpetion must be thrown.

In the example above the element is first added but might be removed again due to size constraints or other elements might be removed, so this violates the contract.

To fix that you might want to change add() and addAll() to throw exceptions in those cases (or maybe in any case in order to make them unusable) and provide alterante methods to add elements which don't violate any existing api contract.

In any case the above example should be used with care since using it with code that isn't aware of the violations might result in unwanted and hard to debug errors.