JAVA uses the Remove method in list to encounter a pit __java

Source: Internet
Author: User

I. Description of the problem


There is a need to filter out from the list of the amount of less than 0.01 of data, looks very simple, I have been doing a half-day, no data has not deleted clean, there will be four or five not deleted.


Ii. Solutions


After testing for half a day, I found the For loop was wrong, and it was written at the beginning:

for (int i = 0; i < psychologistresponselist.size (); i++) {
	double graphicprice = double.parsedouble (psychologistre Sponselist.get (i). Getgraphicprice ())//Graphic price
	double speechprice = double.parsedouble ( Psychologistresponselist.get (i). Getspeechprice ())//Voice price
	Double videoprice = double.parsedouble ( Psychologistresponselist.get (i). Getvideoprice ())//Video Price
	if (1<=graphicprice| | 1<=speechprice| | 1<=videoprice) {
		psychologistresponselist.remove (i);
}

Debug debugging, found that several times before the implementation of the correct, to the last few times, will leak some data ... After searching the Internet, the following is the correct way to do it:

   /
     * * Correct/public
    static void Remove14 (List<string> List, String target) {for
        (int i = list.size ()- 1; I >= 0; i--) {
            String item = list.get (i);
            if (Target.equals (item)) {
                list.remove (item);
            }
        }
        print (list);
     /* Correct
    /public static void Remove22 (arraylist<string> list, String target) {
        final copyonwritearraylist<string> cowlist = new copyonwritearraylist<string> (list);
        for (String item:cowlist) {
            if (item.equals (target)) {
                cowlist.remove (item);
            }
        }
        Print (cowlist);
    }





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.