[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 598
  • Last Modified:

Efficient algorithms to shift items in an arraylist to the left


Let's say that I have an arraylist that has a length of 20.

I am adding 20 items to the list, and it fills up.

Upon adding the 21 item, I would like to discard the item at index 0, and shift all the items over index - 1, and then add the 21st item to the end of the list, and basically maintain this logic for each new item added.

I know that perhaps a linked list would be good for this type of collection, but do you guys have any ideas for how to implement using an arraylist? The reason is because I am using the List object exposed by CollectionBase... and I would like to easily bind this custom collection as a datasource.

  • 2
2 Solutions
gregasmAuthor Commented:
I just threw something together that looks like this:

            public int Add( ThruputData data )
                  if ( List.Count >= MAX_DATAPOINTS )
                        List.RemoveAt( 0 ) ;
                  List.Add( data ) ;
                  return List.IndexOf( data ) ;

What would you do?
so, what's wrong with your approach - you're doing it in the linked list fashion, it will add an item at the end of your array and remove one at the front when it reaches the pick - do you still need any help on this one?

I can't see anything wrong with the solution you've found yourself, it was the first thing I thought of when I read your original question, before I scrolled down the page & saw your solution.

Give yourself the points 8)
gregasmAuthor Commented:
Well, I started off with the datatable approach since it is the first object I think of when databinding. But my datatable solution would be to implement sorting on the table in hidden column, say by timestamp, but this seemed like the approach was too heavy for what I was looking for.. a lightweight implementation.

That's how I got into the custom databinding, and was just wondering what you guys would have done.

Thanks for participating.

Featured Post

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now