Article link: https://liuyueyi.github.io/hexblog/2018/06/07/180607-handwritten fixed-length array/
Handwritten fixed-length arrays
A background scenario is as follows:
A day is divided into 1440 minutes, a data block is recorded every minute, and then a structure is used to store 1440 blocks of data, and over time, every minute, add a piece to the data structure, and remove the first one, and secondly, I want to get forward n-minute blocks of data based on the current time.
Simply put, the above requirements are resolved as follows:
- An array with a capacity of 1440
- Frequent additions and deletions
- Random Access
The next two limits the use of ArrayList and LinkedList, so in order to satisfy this scenario, and then write a simple data structure
I. Sliding fixed-length arrays
To two offsets, the array as a circular structure, a start, an end, respectively recording the start and end, the data is added directly at end, each time the data at the start is deleted, the positioning is calculated with the end or start offset to do, the ultra-simple implementation of the following:
@SuppressWarnings ("Unchecked")PublicStaticClassdarray<t> {Private object[] Arys;Privateint size;Privateint start;Privateint end;@GetterPrivateint capacity;PublicDarray(int size) {this.size = size;This.arys =New Object[size]; Start =0; end = start; Capacity =0; }public void add (T obj) {arys[end] = obj; end = (++end)% size; ++capacity;} public T remove () {if (capacity = 0) {return null;} Object obj = Arys[start]; Arys[start] = null; start = (++start)% size;--capacity; return (T) obj;} public T index (int index) {return (T) arys[( Start + index)% size]; }}
Ii. other ash-gray Blog:https://liuyueyi.github.io/hexblog
A gray and gray personal blog, recording all the study and work in the blog, welcome everyone to visit
Statement
The letter is not as good as, has been on the content, purely opinion, because of limited personal ability, inevitably there are omissions and errors, such as the detection of bugs or better suggestions, welcome criticism, please feel grateful
- Weibo address: small Gray Gray Blog
- QQ: A grey/grey/3302797840
Scan attention Bloginfov2.png
180607-Handwritten fixed-length array