Java ArrayList how to add elements at the beginning

后端 未结 14 1591
忘了有多久
忘了有多久 2020-12-02 06:49

I need to add elements to an ArrayList queue whatever, but when I call the function to add an element, I want it to add the element at the beginning of the arra

14条回答
  •  广开言路
    2020-12-02 07:19

    import com.google.common.collect.Lists;
    
    import java.util.List;
    
    /**
     * @author Ciccotta Andrea on 06/11/2020.
     */
    public class CollectionUtils {
    
        /**
         * It models the prepend O(1), used against the common append/add O(n)
         * @param head first element of the list
         * @param body rest of the elements of the list
         * @return new list (with different memory-reference) made by [head, ...body]
         */
        public static  List prepend(final E head, List final body){
            return Lists.asList(head, body.toArray());
        }
    
        /**
         * it models the typed version of prepend(E head, List body)
         * @param type the array into which the elements of this list are to be stored
         */
        public static  List prepend(final E head, List body, final E[] type){
            return Lists.asList(head, body.toArray(type));
        }
    }
    
        

    提交回复
    热议问题