Which is better ListIterator or Simple list.size() in for loop

Hi everybody
I have one scenario in which, I need to delete the duplicate values from the list (Note : Duplicate values are coming in sequence).
I tried to approaches as follows
1) Using ListIterator
I iterated all values and if I found any duplicate then I called remove() method of Iterator.
2) I made another ArrrayList object, and iterated the old list using size() and for loop, and if I found unique value then I added that value to the new ArrayList.
I also created one test java file to find out the performance in both cases. But I am not pretty sure that this test is correct or not. Please suggest me which approach is correct.
code For Test
public class TestReadonly {
     public static void main(String[] args) {
          List list = new ArrayList();
          long beforeHeap = 0,afterHeap = 0;
          long beforeTime = 0,afterTime = 0;
          addElementsToList(list);
          Collections.sort(list);
          callGC();
          beforeHeap = Runtime.getRuntime().freeMemory();
          beforeTime = System.currentTimeMillis();
          System.out.println(" Before "+System.currentTimeMillis()+" List Size "+list.size()+" heap Size "+beforeHeap);
          new TestReadonly().deleteDuplicated1(list);
          afterHeap = Runtime.getRuntime().freeMemory();
          afterTime = System.currentTimeMillis();
          System.out.println(" After  "+System.currentTimeMillis()+" List Size "+list.size()+" heap Size "+afterHeap);
          System.out.println(" Time Differance "+(afterTime-beforeTime)+" Heap Differance "+(afterHeap-beforeHeap));
          list.clear();
          addElementsToList(list);
          Collections.sort(list);
          callGC();
          beforeHeap = Runtime.getRuntime().freeMemory();
          beforeTime = System.currentTimeMillis();
          System.out.println(" Before "+System.currentTimeMillis()+" List Size "+list.size()+" heap Size "+beforeHeap);
          list = new TestReadonly().deleteDuplicated2(list);
          afterHeap = Runtime.getRuntime().freeMemory();
          afterTime = System.currentTimeMillis();
          System.out.println(" After  "+System.currentTimeMillis()+" List Size "+list.size()+" heap Size "+afterHeap);
          System.out.println(" Time Differance "+(afterTime-beforeTime)+" Heap Differance "+(afterHeap-beforeHeap));
      * @param list
     private static void addElementsToList(List list) {
          for(int i=0;i<1000000;i++) {
               list.add("List Object"+i);
          for(int i=0;i<10000;i++) {
               list.add("List Object"+i);
     private static void callGC() {
          Runtime.getRuntime().gc();
          Runtime.getRuntime().gc();
          Runtime.getRuntime().gc();
          Runtime.getRuntime().gc();
          Runtime.getRuntime().gc();
     private void deleteDuplicated1(List employeeList) {
          String BLANK = "";
          String currentEmployeeNumber = null;
          String previousEmployeeNumber = null;
          ListIterator iterator = employeeList.listIterator();
          while (iterator.hasNext()) {
               previousEmployeeNumber = currentEmployeeNumber;
               currentEmployeeNumber = (String) iterator.next();
               if ((currentEmployeeNumber.equals(previousEmployeeNumber))
                         || ((BLANK.equals(currentEmployeeNumber) && BLANK
                                   .equals(previousEmployeeNumber)))) {
                    iterator.remove();
     private List deleteDuplicated2(List employeeList) {
          String BLANK = "";
          String currentEmployeeNumber = null;
          String previousEmployeeNumber = null;
          List l1 = new ArrayList(employeeList.size());
          for (int i =0;i<employeeList.size();i++) {
               previousEmployeeNumber = currentEmployeeNumber;
               currentEmployeeNumber = (String) employeeList.get(i);
               if (!(currentEmployeeNumber.equals(previousEmployeeNumber))
                         || ((BLANK.equals(currentEmployeeNumber) && BLANK
                                   .equals(previousEmployeeNumber)))) {
                    l1.add(currentEmployeeNumber);
          return l1;
Output
Before 1179384331873 List Size 1010000 heap Size 60739664
After 1179384365545 List Size 1000000 heap Size 60737600
Time Differance 33672 Heap Differance -2064
Before 1179384367545 List Size 1010000 heap Size 60739584
After 1179384367639 List Size 1000000 heap Size 56697504
Time Differance 94 Heap Differance -4042080

I think, you test is ok like that. Although I would have tested with two different applications, just to be shure that the heap is clean. You never know what gc() actually does.
Still, your results show what is expected:
Approach 1 (List iterator) takes virtually no extra memory, but takes a lot of time, since the list has to be rebuild after each remove.
Approach 2 is much faster, but takes a lot of extra memory, since you need a "copy" of the original list.
Basically, both approaches are valid. You have to decide depending on your requirements.
Approach 1 can be optimized by using a LinkedList instead of an ArrayList. When you remove an element from an ArrayList, all following elements have to be shifted which takes a lot of time. A LinkedList should behave better.
Finally, instead of searching for duplicates, consider to check for duplicates when filling the list or even use a Map.
Tobias

Similar Messages

  • Which is better to use in a corprate enviornment for back up Windows 2008 Vs. Mozy

    Which is better to use in a corprate enviornment for back up Windows 2008 Vs. Mozy

    Hi, 
    Microsoft provide the built-in backup utility Windows Server Backup to backup Windows server 2008. For more detailed information, please refer to the articles below:
    Windows Server Backup Step-by-Step Guide for Windows Server 2008
    http://technet.microsoft.com/en-us/library/cc770266(v=ws.10).aspx
    Save big bucks without risk: Get the most from Windows Server 2008 Backup Utility
    http://www.techrepublic.com/blog/data-center/save-big-bucks-without-risk-get-the-most-from-windows-server-2008-backup-utility/
    Please Note: Since the website is not hosted by Microsoft, the link may change without notice. Microsoft does not guarantee the accuracy of this information.
    For Microsoft does not provide any third party software, you need to check with the third party software yourself.
    Regards,
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Turning a linked list into a for loop

    Im stupid and cannot figure out how to make this
    lp list1 = new lp(0,new lp(1, new lp(2, new lp(3, new lp(4, new lp(5, new lp(6, new lp(7, new lp(8, new lp(9, null))))))))));
    into a for loop, i know its simple, i finished my first linked list assignmenet but having this in my program is too ugly and i know a loop should fix it

    JosAH wrote:
    cotton.m wrote:
    Ip list = new IP(9,null);
    for(int i descending order starting from 8 and going down to zero)
    list = new Ip(i,list);
    That last/first element can be in the loop too:
    Ip list = null;
    for(int i descending order starting from 9 and going down to zero)
    list = new Ip(i,list);
    }kind regards,
    Josd'oh! Yes that's better. Thanks.

  • Reasons why to use Iterator for List rather than for loop ?

    when i use the iterator and for loop for traversing through the list. it takes the same time for iterator and also for for loop. even if there is a change it is a minor millisecond difference.
    what is the actual difference and what is happening behind the traversing list through iterator
    if we are using we are importing extra classes ...if we are using for loop there is no need to import any classes

    If you have an array-backed collection, like an ArrayList, then the difference between using an iterator and get() will be negligible.
    However, if you have a linked list, using get() is O(n^2) whereas iterator is O(n).
    So with an iterator, regardless of what your underlying data structure, a list of 100,000 elements takes 1,000 times as long to iterate over as a list with 100 elements. But using get() on a LinkedList, that same 100,000 element list will take 1,000,000 times as long as the 100 item list.
    There's no real benefit to ever using get()
    Side note: I've been comparing iterators to get(), not iterators to for loops. This is because whether it's a for or a while has nothing to do with whether you use an iterator or get(). The way I use iterators is for (Iterator iter = list.iterator(); iter.hasNext(); ) {
        Foo foo = (Foo)iter.next();
    }

  • Which is better hard drive lacie or time capsule for longer life

    hard disk for macbook early 2008

    nvnv0 wrote:
    Is there a error that a questioner himself can click correct answer
    This was discussed in the Using Apple Support Communities forum.  If a questioner finds the answer to his/her own question then he/she can post it for the education of other readers.  However, in so doing, the questioner doesn't get any points.
    Bob

  • Which is better for school and notes pages or ms word

    Hi have a macbook white and i bring this to school and i want to know which is better to use ms word or pages for notes and school work

    If you have used Windows for years and Microsoft Office, then Word will work much better because you will learn to use it quicker than Pages. However, Pages is much cheaper than Microsoft Word, and if you don't mind learning a new interface, then Pages should be enough.
    I use Pages for school projects, and there's one thing that makes a difference: create equations. Pages requires a third-party application like MathType and Word has got a built-in editor, so you should consider this

  • Which has better sound - DVD or highest setting Quicktime?

    Hi (I hope this question did not go through twice) -- I will be engaging in performances where I'll be streaming video and sound from my laptop... my quesiton is - which is better DVD or highest quality Quicktime? - for sound and vid... and by what degree? -- thanks.

    I'll have to say for me it's a tie between my iPhone 3GS and 120 GB (6th gen) iPod Classic. The sound using the Apple in-ear headphones is awesome on those two models. I can't explain why, but that's my observation-there's a marked improvement with those two compared to Nano and older iPod Classic models.

  • In terms of memory utilization which is better to iterate through a LIST?

    For Loop or Iterator Class.?????

    1. For loop and Iterator are not mutually exclusive. One common way to iterate before the foreach loop introduced in 1.5 (my preferred way) was like so:
    for (Iterator iter = list.iterator(); iter.hasNext();) {
      Object obj = iter.next();
    }2. By "for loop" I assume you mean "using get()". NEVER iterate using get(). It will work fine on ArrayList, but will be crappy slow on LinkedList, and doesn't exist on Set or Collection. Using an Iterator (or foreach, which is syntactic sugar for an Iterator) means you'll get proper and consistent behavior on any colleciton.
    3. The memory usage will not be any different, or will be ridiculously insignificant. This kind of microoptimization without hardcore profiling numbers is a good way to gain a tiny, meaningless bit in one area at a much larger cost in another area.
    Just use a foreach loop, or in cases where you need to modify the collection under iteration, an explicit Iterator or ListIterator.

  • Droplet or Simple Nucleus component which is better ?

    Hi,
    1)Droplet or Simple Nucleus Component which is better as per memory utilization (performence wise).
    2)extending one  Droplet in another droplet is recomended or injecting droplet which is recomended ?
    Please clear these issues if any body ASAP.
    thanks

    Hi,
    Droplets are intended to connect front end (jsps) with the business functionality thro nucleus components. They are primarily used for presentation logic which involves business rules.
    So, you need to decide to go for a mere nucleus component or droplet based on your requirement.
    It is good to have any business logic / common code in a tools class and call that method from the droplet. In this case, you do not need to extend other droplet and can reuse the code from the tools class by injecting the tools component.
    Please let me know if this helps. Or else, please specify the requirements more specifically.
    Hope this helps.
    Keep posting the updates.
    Thanks,
    Gopinath Ramasamy

  • Coding Preference ..Which is better for memory?

    Hey all,
    Javas garbage collection is sweet. However, I was reading somewhere that setting some objects to null after I'm done with them will actually help.
    (help what .. I'm not sure.. my guess is memory used by the JVM)
    Thus I have two ways to do the same thing and I'd like to hear peoples comments on which is "better" ... or will yield faster performance.
    Task: I have a Vector of Strings (called paths) that hold absolute file paths. (Don't ask why I didn't use a String[]) I'd like to check and see if they exist, and if not, create them... I'll use the createNewFile() method for that.
    Method A -- Here I'll reuse that File object
    public void myMethod()throws Exception{
    File file = null;
    for(int i = 0; i < paths.size(); i++){
      file = new File(paths.get(i).toString());
      boolean made  = file.createNewFile();
      if(made){doSomething();}
    file = null;
    }Method B -- Here I'll use um... "dynamically made" ones that I won't eventually be set back to null
    public void myMethod()throws Exception{
    for(int i = 0; i < paths.size(); i++){
      boolean made  = (new File(paths.get(i).toString())).createNewFile();
      if(made){doSomething();}
    }So when the code eventually exists myMethod, the object "file" will be out of scope and trashed.... correct? If thats the case, then would there be any other differences between the two implementations?
    Thanks

    There's no real difference between the two. Choose the style you prefer,
    although in the first one I'd lose the "file = null" statement since that
    variable is about to disappear, and I'm move the definition into the loop
    -- always give variables as small a scope as possible, mainly to
    keep the logic simple:
    public void myMethod()throws Exception{
        for(int i = 0; i < paths.size(); i++){
            File file= new File(paths.get(i).toString());
            boolean made  = file.createNewFile();
             if(made){doSomething();}
    }

  • Which is better to Learn STRUTS or JSF??

    I have a very robust/simple shopping cart application that I want to upgrade.
    It currently uses simple bean classes(get/set), action servlets, and jsp for the client(frontend).
    I am trying to upgrade small features, for example, adding a Google type results displaying 10 at a time.
    first previous 12345678910 next last Which would be better to learn?? Both, or is one better than the other??

    well,
    there's no better choice.
    the technology you should choose depends on many things.
    for example, you allready have your application up and running. if you upgrade some part of it to JSF you will probably not be able to deploy/sell your app because JSF might still be in beta.
    you should make a list of criteria for your self and try to give points for each criteria in both technologies, sum it up and you will have your answer.

  • Which Is Better Time Machine or Backup

    So I just got a new iMac plus a 1T external drive. I have been using backup on my old mini-mac with an external drive plus I used the drive for iTunes and iPhoto. So which is better TM or the old backup (which I had no problems with). I really do not do a lot on the iMac, no work just iLife stuff.
    If I use TM can I partition the 1T to use one 500 GB for TM and another 500 GB for any odds and ends I simply want to store there (I plan to convert old videos to digital)?
    Thanks

    Hi! The drive for a bootable clone should be the same size as the internal main drive as should be the drive for TM. To create a bootable clone you can use the disk utility but I prefer SUPERDUPER and if you pay the 27.95 you get the ability to schedule auto backups! Tom
    To use the disk utility: Kappy's method
    How to Clone Using Restore Option of Disk Utility
    1. Open Disk Utility from the Utilities folder.
    2. Select the backup or destination volume from the left side list.
    3. Click on the Erase tab in the DU main window. Set the format type to Mac OS Extended (journaled, if available) and click on the Erase button. This step can be skipped if the destination has already been freshly erased.
    4. Click on the Restore tab in the DU main window.
    5. Select the backup or destination volume from the left side list and drag it to the Destination entry field.
    6. Select the startup or source volume from the left side list and drag it to the Source entry field.
    7. Double-check you got it right, then click on the Restore button.
    8. Select the destination drive on the Desktop and press COMMAND-I to open the Get Info window. At the bottom in the Ownership and Permissions section be sure the box labeled "Ignore Permissions on this Volume" is unchecked. Verify the settings for Ownership and Permissions as follows: Owner=system with read/write; Group=admin with read/write; Other with read-only. If they are not correct then reset them.
    For added precaution you can boot into safe mode before doing the clone.
    Message was edited by: Thomas Bryant

  • Which is better ? for loop or iterator ??

    Hi,
    I have one array list having more than 100 objects in it.
    I have two way to ietrator.
    1.
    for(int i=0; i<list.size(); i++)
    Object o = list.get(i);
    2.
    Iterator i = list.getIterator()
    while(i.hasNext())
    Object o ...
    which is better in performance ??

    Well okay. It's an easy optimization but I guess Sun
    doesn't want to "bail out" people who don't know
    their data structures.It won't always be optimal, though. If you use
    iterators and don't iterate the whole way through
    every time, it would degrade performance. It's hard
    for them to make assumptions about how you will
    access the data. So you punish people who do use it
    properly if you do that.I don't know. The optimization I suggested is isolated to random accesses in the linked list only. Say you access index 5. The node pointer corresponding to 5 is stored and if the next access is index 6 the node pointer you're looking for is pointer.next. There's no need to walk the list from the beginning.

  • Xerces or JDOM which is better?

    hi all
    i would like to ask for some opinions.
    Xerces and JDOM which is better?
    thanks!

    This dude is right. JDOM6 is the bomb.
    here is a little present:
    import java.io.*;
    import java.io.File;
    import java.util.List;
    import java.util.Iterator;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.adapters.*;
    import org.jdom.adapters.CrimsonDOMAdapter;
    import org.jdom.input.DOMBuilder;
    import org.jdom.output.XMLOutputter;
    public class xmltest
    // Global value so it can be ref'd by the tree-adapter
    public static Document document;
    public static DOMBuilder builder;
    public static String product_name, description, price;
    public static Double checkPrice;
    public static void readDoc()throws IOException, JDOMException
    builder = new DOMBuilder();
    try {
    FileInputStream in = new FileInputStream(new File("settings.xml"));
    document = builder.build(in);
    in.close();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    public static void listProducts()throws IOException, JDOMException
    readDoc();
    Element root = document.getRootElement();
    List products = root.getChildren();
    Iterator productsIterator = products.iterator();
    System.out.println("Currently " + products.size() + " products.");
    while(productsIterator.hasNext()){
    Element productElement = (Element)productsIterator.next();
    List product = productElement.getChildren();
    System.out.println(productElement.getTextTrim());
    Iterator productIterator = product.iterator();
    while(productIterator.hasNext()){
    Element attElement = (Element)productIterator.next();
    System.out.println(attElement.getName() + " : " + attElement.getText());
    public static void removeProduct(String productName)throws IOException, JDOMException
    readDoc();
    Element root = document.getRootElement();
    List products = root.getChildren();
    Iterator productsIterator = products.iterator();
    root.removeChildren();
    while(productsIterator.hasNext()){
    Element tempElement = (Element)productsIterator.next();
    if(!tempElement.getTextTrim().equals(productName)){
    root.addContent(tempElement);
    document.setRootElement(root);
    saveChanges();
    public static void addProduct(String product_name, String description, String price)throws IOException, JDOMException
    readDoc();
    Element product = new Element("product");
    Element root = document.getRootElement();
    product.addContent(product_name);
    product.addContent(new Element("description").addContent(description));
    product.addContent(new Element("price").addContent(price).addAttribute("currency", "US"));
    root.addContent(product);
    saveChanges();
    public static void saveChanges(){
    try {
    XMLOutputter outputter = new XMLOutputter();
    FileWriter writer = new FileWriter("settings.xml");
    outputter.output(document, writer);
    writer.close();
    } catch (java.io.IOException e) {
    e.printStackTrace();
    public static void main(String argv[])throws IOException, JDOMException
    int selection;
    for(;;){
    System.out.println("1. Add a product\n2. Remove a product\n3. View products\n4. exit program");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    try{
    selection = Integer.parseInt(in.readLine());
    switch(selection){
    case 1:
    System.out.println("Enter product name.");
    product_name = in.readLine();
    System.out.println("Enter product description.");
    description = in.readLine();
    System.out.println("Enter product price.");
    price = in.readLine();
    try{
    checkPrice = new Double(price);
    addProduct(product_name, description, price);
    }catch(Exception e){
    System.out.println("The product's price must be a numeric value.");
    break;
    case 2:
    System.out.println("Enter product name to remove.");
    product_name = in.readLine();
    removeProduct(product_name);
    break;
    case 3:
    listProducts();
    break;
    case 4:
    System.exit(1);
    break;
    default:
    System.out.println("The number you have typed is incompatible with the menu.");
    break;
    }catch(Exception e){
    System.out.println("Please type in a number that maches the menu.");
    enjoy....

  • Triggers or Programs, which is better?

    Hello,
    I have a simple question, say, I have 40Mil records to process or even higher and which is better, to have the functions in a program that reads the database or as a database triggers with functions?
    How good is Oracle to process 200Mil records or more?
    Thanks.
    -Nair

    I couldn't understand your problem. Anyway a trigger is attached to the table, so whenever you have an action updating a table the trigger automatically fires. On the other hand a program or function is an outer entity and must be loaded and run to make process whatever request/modification to your table.
    Oracle databse is capable of working with very large volumes of data. Refer to the manuls to get accurate info.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Unni Krishnan ([email protected]):
    Hello,
    I have a simple question, say, I have 40Mil records to process or even higher and which is better, to have the functions in a program that reads the database or as a database triggers with functions?
    How good is Oracle to process 200Mil records or more?
    Thanks.
    -Nair<HR></BLOCKQUOTE>
    null

Maybe you are looking for

  • Material Ledger - Closing Postings

    Dear Material Ledger Experts, I need to clear my concepts regarding Material Ledger Closing Postings : Standard Price of Finished Goods : $10 Produced Units via Process Order: 1000 Units Variance Settled to P&L Accounts : $1 Per Unit P.G.I Units : (3

  • High parse to execute ratio

    Hi I am using TOAD on my Apex database to check performance of database.. And my PRD system has a 99.7% Parse to Execute ratio, where my UAT system only has a 17% ratio I did this query SELECT parse_calls, executions, sql_text   FROM v$sql WHERE exec

  • Program name for fill up setup table vistex agreement datasources

    Dear all, Am using the Vistex agreement data source in which i want to retrieve the data into BI landscape. For my concern i have seen one article, http://www.sdn.sap.com/irj/scn/index?rid=/library/uuid/30a25b51-c5e8-2c10-d485-de4c69a78728 i can able

  • Change print order when printing multiple photos

    Hi, I am printing multiple duplex pages in Photoshop Elements 6 but cannot get them to print in the correct order. Can anyone help me? Tracey

  • Finder Deletes items immediately

    I was having some issues and while trying to fix it I used a terminal command that I can't remember. Now whenever I want to send a file to the trash, i get a message asking to confirm and that the file will be deleted immediately. If someone could te