简体   繁体   中英

Java - Data structure design - Fixed size, random access, thread safe, sorted collection

So, in some question I was required to implement the following: Data structure of fixed size (n=10), that is always ordered (descending, not that it matters), thread safe, and supports random access.

My solution was - using a TreeSet , whenever adding an element, if there are already n elements, remove the smallest element (if the new element if bigger than it) and add the new element. Otherwise, just add the new element. When accessing a random index, use the TreeSet iterator to iterate until the required index.

I don't like this solution so much. So I thought of another solution: Using an ArrayList , constructed with the size of n . Whenever trying to add an element, do a Collections.binarySearch() for the element and insert it if it doesn't exists, using the index returned from binarySearch. If after adding the element the list length is bigger than n (equals n+1 actually), remove the smallest element (which is on the end of the list). This way, we get log(n) for add (same as TreeSet from previous solution) and random access is O(1). Only thing I don't like about it is that the add() for an arbitrary index in the middle of the list requires shifting all the elements after it. (works well for small n but for big n maybe not?)

For both solutions I use ReentrantReadWriteLock - acquire writeLock() for add and readLock() for the get() / read operations.

Is there a better solution?

**

Collections.synchronizedList(List i) makes the passed argument a threadsafe List.

you can implement the comparable interface when creating your class and override compareTo() method in a way that it orders the element by descending order when you are adding them to the ArrayList<>() or you can go for Comparator class and overriding compare() method while sorting it.

In the total collection, only List(I) supports RandomAccess.

ArrayList<Employee> arrayList = Collections.synchronizedCollection(new ArrayList<Employee>(10));

and if you want the same item should not be added to the ArrayList use Comparator and return 0 when a new item (want to add) and last item (already added) is equal. handle the return value in such a manner that if (...==0){ don't add to the data ) else { add it }. I hope I could give u some hint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM