Why is there no SortedList in Java?

后端 未结 12 786
猫巷女王i
猫巷女王i 2020-11-22 04:15

In Java there are the SortedSet and SortedMap interfaces. Both belong to the Java Collections framework and provide a sorted way to access the elements.

However, in

12条回答
  •  清酒与你
    2020-11-22 04:49

    In case you are looking for a way to sort elements, but also be able to access them by index in an efficient way, you can do the following:

    1. Use a random access list for storage (e.g. ArrayList)
    2. Make sure it is always sorted

    Then to add or remove an element you can use Collections.binarySearch to get the insertion / removal index. Since your list implements random access, you can efficiently modify the list with the determined index.

    Example:

    /**
     * @deprecated
     *      Only for demonstration purposes. Implementation is incomplete and does not 
     *      handle invalid arguments.
     */
    @Deprecated
    public class SortingList> {
        private ArrayList delegate;
    
        public SortingList() {
            delegate = new ArrayList<>();
        }
    
        public void add(E e) {
            int insertionIndex = Collections.binarySearch(delegate, e);
    
            // < 0 if element is not in the list, see Collections.binarySearch
            if (insertionIndex < 0) {
                insertionIndex = -(insertionIndex + 1);
            }
            else {
                // Insertion index is index of existing element, to add new element 
                // behind it increase index
                insertionIndex++;
            }
    
            delegate.add(insertionIndex, e);
        }
    
        public void remove(E e) {
            int index = Collections.binarySearch(delegate, e);
            delegate.remove(index);
        }
    
        public E get(int index) {
            return delegate.get(index);
        }
    }
    

提交回复
热议问题