Iterator remove versus ArrayList clear

Hi,
I iterate through an ArrayList, and the last thing I do is call (Iterator)it.remove(). I am wondering if the performance is better, worse, or equal to if I was to not call it.remove() but instead just clear() the ArrayList after exiting the loop.
Can someone tell me the tradeoffs, or if they are equal? I am interested in performace.
Thanks.

Since you'd have to call remove once for every element in the list, I would think that clear would be faster.
However...
* Put it on a profiler or mark start/end time on a lage list to get a concrete mesaurement, rather than guessing.
* If possible, just getting rid of the list and creating a brand new one when you need it will probably be better than either of the other methods.
* This is a microoptimization that should only be done after a profiler tells you that this is a bottleneck. Until then, use whichever idiom more closely matches your intent.

Similar Messages

  • What is the difference between iterator.remove() ArrayList.remove()?

    Following code uses iterator.remove() ArrayList.remove().
    public class CollectionRemove
        private static void checkIteratorRemove()
             List<String> list = new ArrayList<String>();     
              list.add("1");
              list.add("2");
              list.add("3");     
             System.out.println("in checkWithIterator*************");
            Iterator<String> iter = list.iterator();
            while (iter.hasNext()) {
                String str = iter.next();           
                if (str.equals("2")) {
                    iter.remove();
                System.out.println("list Size: " + list.size() + " Element: " +  str);
        private static void checkListRemove()
             List<String> list = new ArrayList<String>();     
              list.add("1");
              list.add("2");
              list.add("3");     
            System.out.println("in ncheckWithForLoop*************");
            Iterator<String> iter = list.iterator();
            while (iter.hasNext()) 
                 String str = (String) iter.next();    
                if (str.equals("2")) {
                    list.remove(str);
                System.out.println("list Size: " + list.size() + " Element: " +  str);
        public static void main(String args[])
             checkIteratorRemove();
             checkListRemove();
    output is :
    in checkWithIterator*************
    list Size: 3 Element: 1
    list Size: 2 Element: 2
    list Size: 2 Element: 3
    in ncheckWithForLoop*************
    list Size: 3 Element: 1
    list Size: 2 Element: 2Why is this difference ? what is the difference between iterator.remove() ArrayList.remove()?

    In the case of Fail-fast iterator, if a thread modifies a collection directly while iterating over it, the iterator will thow ConcurrentModificationException . Say,
    for (Iterator it = collection.iterator(); it.hasNext()) {
        Object object = it.next();
        if (isConditionTrue) {
            // collection.remove(object);  can throw ConcurrentModificationException
            it.remove(object);
    }As per specs,
    Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will thow this exception.

  • Error message "Your start up disc is full please remove files to clear"which I have done but no joy?

    Error message "Your start up disc is full please remove files to clear"which I have done but no joy?

    Thanks for the advice and yes I did empty trash,clear excess files deleted old e-mails the works!!! Eventually traced to a faulty e-mail file which was giving a false reading that was using 930GB,s out of 999GB,s and thus the reading I was getting!! the answer involved advice from Apple over the phone I had to trash a huge e-mail file so my reading is now 929GB,s free out of 999GB,s  Thanks again. wheelspanner

  • Iterator remove

    hi there, i posted this topic a while back but now i am needing to use it, it don't work.
    public String    subtractFromStock(String serial) {   
                        Iterator getSN = theComputers.iterator();               
                    while(getSN.hasNext())                 {
                    Computer comp = (Computer)getSN.next();                 if(serial.equals(comp.getSerial()))                 {
                          Iterator.remove();
                          ConsoleIO.out.println("Serial Number " + comp.getSerial() + " Has been removed from the system");
                      inventory();
            return null;I heard someone say use the Iterator.remove() as I have done there but it doesn't work:
    Shop.java:67: non-static method remove() cannot be referenced from a static context
                      Iterator.remove();
                              ^
    1 errorany ideas?

    instead of Iterator.remove(), try getSN.remove().
    although, i didn't look at your code long enough to try to understand what you're trying to do.
    the error message was very specific though...

  • Removing Private Browsing, Clear Cache, etc. options from Safari

    This was discussed earlier, but the situation just came back up here at school as students have been found clearing history etc. to cover their tracks. This was originally posted by Yang in May 2006.
    "If you have the developer tools installed, or more specifically, Interface Builder, you can easily remove the 'Private Browsing' and 'Reset Safari' menu-items. Create a copy of Safari and browse to '/Safari.app/Contents/Resources/English.lproj/'. Open MainMenu.nib in Interface Builder. In the template of the menu bar which appears, browse to and highlight each menu-item and hit backspace to delete. Save and quit. That Safari application package will now be missing the menu-items.
    You can replace the original Safari package with the modified one, and maybe have the unmodified version in the 'Applications' folder of an administrator's home folder.
    Unfortunately, the 'Clear History' menu item seems to be generated dynamically. I can't seem to find the reference to it in Safari's resources. However, that said, I believe there are more elegant solutions to tracking a user's browsing history. In fact, it might be advisable to look at third-party solutions - ones which write history to a separate file. For instance, even if the menu-items are missing, it is possible to simply trash the relevant .plist after each browsing session to remove all traces of its history."
    In doing that, I found that while you can't remove the dynamically created "Clear History" from the History Menu, you can open "/Safari.app/Contents/Resources/English.lproj/Localizable.strings" with Project Builder from the Developers Tools and edit what shows in the menu. Just change what is after the = sign for the items you want to change and save it. It may not stop the practice completely, but it will slow things down. (Students may think twice before selecting a menu option that says "Permanently Archive History".) This doesn't change the function, just what it is called on the screen. I also removed "Empty Cache..." from the menu and changed the label and icon for History when you "View All Bookmarks" to reduce deleting them through that method. It makes them harder to find.
    Just be sure you are modifying a copy of the App so you keep the original. I then used Remote Desktop to copy the modified application into the Applications folder on the student computers. So far, only limited testing, but everything seems to work at this point.
    By the way, this was my first experience with Developers Tools and they really aren't that daunting if you think things through first.

    Seems I'm out of touch with school day issues.
    It appears you would rather snoop on behavior and punish Web "wrongdoers" than let students imagination and a few "rules" guide their Web experiences.
    If a child is smart enough to know how to "cover their tracks" then they've learned something wrong from your instructors.
    You may just want to take away their browsers and replace them with:
    http://www.makienterprise.com/kggg/kidsgogogo.html
    You also mention Apple Remote Desktop in your post. It allows you to view what any machine is doing.
    Instructor is not at a machine taking a "peak" over the students shoulder? Worked when I was in school.

  • Memory management HashMap versus ArrayList.

    Hopefully this is the right place to post this!
    Okay, here is my question. I have been trying to research on the memory hit an application is going to incur if it uses a HashMap instead of an ArrayList and I have not been able to find a satisfactory answer.
    Suppose I have say 10,000 objects and the way I access them is such that 50% of time I end up iterating through the whole list, and the other 50% I have to access its entries randomly, then what should I opt for a HashMap or an ArrayList?
    The way the data is stored in my HashMap is such that a String is used as a key. So according to me, at the very least not including HashMap�s internal overhead I am going to waste memory just by creating a String object to represent the �Key� and I would be better of using an ArrayList in terms of memory utilization and will not experience a major performance hit.
    Does anyone have a take on this?

    Cross-post
    http://forum.java.sun.com/thread.jspa?threadID=5190383

  • ArrayList clears when placed in HashMap

    I have a series of ArrayLists (argValues), to be used as the values in a HashMap. They are not empty when they are placed in the table, but when I try to get one of them out, the ArrayList that is returned is empty. Here is the part of my code that has the problem. I'm parsing an XML file beforehand (doc_cmd is the Document into which the XML was parsed):
               NodeList nl_cmd = doc_cmd.getElementsByTagName("RFSW_CMD_PKT");
               if (doc_cmd != null) {
                   for(int i = 0; i < nl_cmd.getLength(); i++) {
                        if (!nl_cmd.item(i).getNodeName().equals("#text")) {
                            String key = nl_cmd.item(i).getAttributes().getNamedItem("NAME").getNodeValue();
                            //   System.out.println(key);
                            Element currentCmd = (Element) nl_cmd.item(i);
                            NodeList nlChildren = currentCmd.getChildNodes();
                            ArrayList argValues = new ArrayList();
                            for (int j = 0; j<nlChildren.getLength(); j++) {
                                if (!nlChildren.item(j).getNodeName().equals("#text")) {
                                    nodeName = nlChildren.item(j).getNodeName();
                                    if (!nodeName.equals("BITFIELD") && !nodeName.equals("UNION"))
                                        argName = nlChildren.item(j).getAttributes().getNamedItem("NAME").getNodeValue();
                                    else
                                        argName = "";
                                    value = nodeName + "_" + argName;
                                    argValues.add(value);
                            // THIS IS WHERE THE PROBLEM IS
                            System.out.println("ARGVALUES SIZE = " + argValues.size());
                            hashcmds.put(key, argValues);
                            argValues.clear();
                            ArrayList yo = (ArrayList)hashcmds.get(key);
                            System.out.println("SIZE = " + yo.size());

    Note that you're calling the clear method on the
    object you've inserted, not a copy of it. You should
    clone() itIn this case I there is no point in cloning the ArrayList because it goes out of scope. He isn't resuing it and there was never a reason to clear it anyway. The solution is to just not clear the ArrayList.
    If one were attempting to reuse it in that manner, cloning an ArrayList and clearing it to use again is less efficient than just creating a new one and letting the old one go out of scope.
    The steps required to fill clone and reuse.
    1. create new ArrayList
    2. copy references
    3. clear entries
    4. insert n refereneces
    The steps required to just create new
    1. create new ArrayList
    2. insert n references
    By clearing the ArrayList here, you are just doing more work.

  • For-loop & iterator.remove()

    Is it possible to remove an item during iterating with for-loop?
    for (SelectionKey opKey : selector.selectedKeys())
         // I need to remove opKey from selectedKeys set.
    }Is it really necessary to remove handled key from selectedKeys set? What will happen if I run selector.select() while selectedKeys set contains some keys?

    Desiderata wrote:
    Is it possible to remove an item during iterating with enhanced-for-loop?No
    Is it really necessary to remove handled key from selectedKeys set? What will happen if I run selector.select() while selectedKeys set contains some keys?[Selector Selection|http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/Selector.html#selop]

  • Remove from ArrayList

    How would I go about removing an element from an arraylist via an element's value (a long in this case) instead of the index value? Is it possible? If not, how do I get the index of a particular element then?
    Thanks.

    Sorry, should have been more specific. Each element is actually an object...
    private class userStructure implements Serializable
          public long userId;
          public int userStatus;
          public userStructure (long usersId, int status)
            userId= usersId;
            userStatus= status;
          public long getUserId(){return userId;}
          public int getUserStatus(){return userStatus;}
        }I'm trying to remove the object from the list via the long userId.

  • 8520 - removing email addresses/clearing phone

    Sorry, long and very boring story!
    I had a Blackberry 8520 which my horse kindly deposited in his waterbucket, and I then discovered it wasnt insured.   The main "mouse" type button stopped working, so I had to buy another.
    I used the application on my desktop to transfer over my email addresses and what have you, all seemed very simple (which it has to be for me!) but I havent received any emails to my new device since, despite the fact the icons are there for the addresses.
    I dont think I cleared the old phone so wonder if the emails are going there (I cant see as I cant use the button!)
    I found some instructions on the Blackberry website about removing the email from the device.  I cant do it ON the device due to the button issue, the other solution suggested doing it on the Blackberry Internet Service Web Site - and I dont mean to sound thick but someone else set the initial blackberry up for me who I cant now get hold of - but I have no idea where it is telling me to look as I cannot find "Settings" or "Email Accounts" on that website?
    I am sure this is much more simple than my little brain is making it! Can someone help please?
    Thanks

    smokeysbandit wrote:
    the other solution suggested doing it on the Blackberry Internet Service Web Site
    Smokey, look here: 
    To delete the BIS email account:  http://www.blackberry.com/btsc/KB04620
    To login to your service provider: See the section that reads
    "Set up your BlackBerry Internet Service account from your
    computer"
    http://www.blackberry.com/btsc/KB03087
    NOW, even thought your trackpad may not work to click, can it scroll around the homescreen icons?
    If so, you can use the ENTER key (lower right) to open most icons, try it.
    1. If any post helps you please click the below the post(s) that helped you.
    2. Please resolve your thread by marking the post "Solution?" which solved it for you!
    3. Install free BlackBerry Protect today for backups of contacts and data.
    4. Guide to Unlocking your BlackBerry & Unlock Codes
    Join our BBM Channels (Beta)
    BlackBerry Support Forums Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • ArrayList - clear() or new ArrayList() ?

    Hi everybody,
    I have a loop which runs ~100-100000 times and in each looping an ArrayList is filled and holds elements ranging from 1 to 30000. I'm reusing the list and I'm wondering whether I should use clear() or better reinstantiate the List.
    I know that with StringBuffer the setLength(0) does not decrease the capacity of the StringBuffer, so that it might take much more memory than it actually needs.
    How about List?
    Does clear() decrease the capacity of the List?
    Would a reinstantiation be the better way?
    Or doesn't it matter anyway and a list with too much capacity is fine to use?
    Hope you can help
    Cheers
    bgcl

    Hi everybody,
    I have a loop which runs ~100-100000 times and in each
    looping an ArrayList is filled and holds elements
    ranging from 1 to 30000. I'm reusing the list and I'm
    wondering whether I should use clear() or better
    reinstantiate the List.
    I know that with StringBuffer the setLength(0) does
    not decrease the capacity of the StringBuffer, so that
    it might take much more memory than it actually
    needs.
    How about List?
    Does clear() decrease the capacity of the List?
    Would a reinstantiation be the better way?
    Or doesn't it matter anyway and a list with too much
    capacity is fine to use?
    Hope you can help
    Cheers
    bgclclear() will be better than new ArrayList() but the performance difference of clear() and new ArrayList(int) (with an int of an appropriate size) will be negligable.

  • Remove password in clear text warning.

    After I bound my Lion Server to an AD account and set it up for Profile Manager (http://support.apple.com/kb/HT4837) I have a warning message when i login saying that my password will be sent in clear text. I want to get rid of this message. I have SSL enabled and the login page is HTTPS. Any ideas how to fix this?

    Balendran,
              Sorry for the confusion. The issue was not that passwords were in clear text inside the wli-ra.xml. The problem was that the password was displayed in clear text on one of the configuration windows of WLI.
              For example, the DBMS adapter (the sample adapter shipped with WLI) has a property called "Password" in the wli-ra.xml:
              <?xml version="1.0" encoding="UTF-8"?>
              <connector>
              <resourceadapter>
              <config-property>
              <config-property-name>Password</config-property-name>
              <config-property-type>java.lang.String</config-property-type>
              <config-property-value></config-property-value>
              </config-property>
              </resourceadapter>
              </connector>
              When you try to configure Event Connection, one of the pages that come up is called "Configure Event Delivery Parameters", and on which it listed all the properties in the above wli-ra.xml for you to fill in values. As you type in the values for the Password property (as for all other properties), the value is displayed as clear text on the screen. That's the issue I am trying to solve. Any suggestions?
              Thanks.
              Yongtao

  • My (shared) iMessages are taking up almost all my iPhone storage. Is there a way to remove them to clear up some space on my phone?

    My (shared) iMessages are taking up almost all my iPhone storage. Is there a way to remove them to free up space on my phone?

    Thx - the videos are on my Ipad - that is the problem - they are taking up all the storage and there is no room for anything else. Is there any place I can store them so that I can access them from time to time, but not have they use up all the space on the IPad? Sounds like the cloud is out...

  • Photoshop Elements 12 crashing in slideshow (either preview or output).  I've updated Windows, Windows Media Player, Video Driver, Elements 12 - all are updated.  I've tried removing plug-ins, cleared temporary internet files.

    PhotoshopElementsOrganizer.exe
    12.0.0.0
    5314d4d4
    ntdll.dll
    6.3.9600.17668
    54c846bb
    c0000005
    00041eee
    1574
    01d061d37b85a960
    C:\Program Files (x86)\Adobe\Elements 12 Organizer\PhotoshopElementsOrganizer.exe
    C:\Windows\SYSTEM32\ntdll.dll
    dbffe386-cdc6-11e4-828a-8086f2117550

    You originally posted on a thread that really wasn't related to your problem, so I branched the discussion.
    Check the Windows System Event Viewer to see the details of the crash, most importantly the name of the faulting module.
    Most crashes on Open or Save are due to OS bugs (especially on MacOS) or bugs in third party extensions to the OS open and save dialogs.

  • Crashes when utilizing saved passwords or password prof\gran "ROBOFORM". Is there a Firefox removal process to clear its previous registry entries to get a fresh start?

    Using Win XP. Not sure what other info to provide.
    P.S. "password prof/gran" should read "password program"

    I understand the inconvenience you are experiencing when working with Office 2013.
    If you have any feedback about Office 2013 product, click the and submit to Microsoft.
    Microsoft will decide how to fix the problem for all customers.
    For the activation mechanism, it intends to protect customers of their rights and interests.
    For a retail version of Office, if it was purchased with a disk, Microsoft account is not necessary during the installation.
    For volume license of Office, refer to the following link to deploy Office suites can be much efficient:
    http://technet.microsoft.com/en-us/library/cc178982.aspx
    For the problem Office 2013 keep crashing, check the following link to check:
    http://support.microsoft.com/kb/2813143/en-us
    http://support.microsoft.com/kb/2758592/en-us
    Thanks,
    Tyor Wang
    Forum Support
    Come back and mark the replies as answers if they help and unmark them if they provide no
    help.
    If you have any feedback on our support, please click
    here

Maybe you are looking for