Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6902917
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T07:51:31+00:00 2026-05-27T07:51:31+00:00

i’m looking for an implementation of SortedSet with a limited number of elements. So

  • 0

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());
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T07:51:32+00:00Added an answer on May 27, 2026 at 7:51 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
In my XML file chapters tag has more chapter tag.i need to display chapters
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I would like to count the length of a string with PHP. The string
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.