How to Implement the Remove Method in arraylist

Source: Internet
Author: User
Source code of the arraylistremove method:
 
Public Boolean remove (Object O) {If (O = NULL) {for (INT Index = 0; index <size; index ++) if (elementdata [Index] = NULL) {fastremove (INDEX); return true ;}} else {for (INT Index = 0; index <size; index ++) if (O. equals (elementdata [Index]) {fastremove (INDEX); return true ;}} return false ;}

First of all, find the subscript of the object to be deleted. After all, in Java, the List Implementation is implemented using arrays. What does it mean to delete an element, this means that all elements after the element subscript to be deleted are moved to the previous position:

Private void fastremove (INT index) {modcount ++; int nummoved = size-index-1; if (nummoved> 0) system. arraycopy (elementdata, index + 1, elementdata, index, nummoved); elementdata [-- size] = NULL; // Let GC do its work}

Elementdata [-- size] = NULL; after all the elements to be deleted are moved one by one, the last element is set to null. The following is testsystemcopy. Java:

 
Package testsystem; public class testsystemcopy {public static void main (string [] ARGs) {string [] strarr = new string [] {"1", "2", "3 ", "4", "5", "6", "7", "8", "9"}; // move the element with the subscript 4 to a system. arraycopy (strarr, 3, strarr, 2, strarr. length-3); strarr [strarr. length-1] = NULL; For (INT I = 0; I <strarr. length; I ++) {system. out. println (strarr [I]) ;}}

Array is used in arraylist.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.