Same things in a linked list

i have a linked list and i am adding to it all the time. The list holds objects that contain a string and a int. When i add an object i want to check to see if an object already exists with the same value in the string. If there is i increment the int and dont add the new object. Does anyone have any helpful code or suggestions????

You could either use List.contains, or you could just use a Set instead of a List. (See the API docs for both to determine which is more suited to your needs.)
Either way, you'll have to override equals() and hashCode() on your object.
See this chapter in Josh Bloch's book for some good tips on what to put into those methods

Similar Messages

  • Is it possible to implement or represent a Linked List in LabVIEW?

    Linked lists are a useful way to store and retrieve data and I am wondering if it is possible to create or acheive the same objective of a linked list in LabVIEW.

    A linked list is a collection of nodes, each node has data and a link (or pointer) to the location of the next node.
    In LabVIEW we can create a collection of nodes as an array of clusters. One element of the cluster will be our data, and the other will be an integer pointer to the location in the array, of our next node.
    In, fact you can go crazy and represent a LabVIEW Hierarchy in a similar fasion (a tree structure). Now, each cluster will have data about the VI (its Name, attributes, etc), an array of integers that point the the locations of calling VIs, and an array of integers that point the the locations of subVIs.
    You will, of course also need some tools for sorting your lists/trees and performing useful operations... lot's of fun!
    Good luck
    Jim

  • Linked List  - deleeting nodes - HELP!

    How do I delete all occurences of the nodes with the same parameters in the linked list ?
    example:
    Node1-> Node2 ->Node3->Node4->Node5
    Node1, Node4, and Node5 have the same String value, how do I delete them in one method without breaking the linked list ?
    thanks

    Hi,
    You have iterate thru the linked list remove one by one. Also have look at other collection classes like HashSet or HashMap for fast retrieval.

  • Elements overwrites each others in Linked List

    hello, my problem is mentioned as the subject.
    i'm trying to add the same object into a linked list each time with different values, however it doesn't work and eventually all objects stored in the linked list become identical.
    here's the sample code.
    public class Object1
         private String s = null;     
         public Object1(){}
         public void setS(String s){this.s = s;}
         public String getS(){return s;}
    import java.io.*;
    import java.util.List;
    import java.util.LinkedList;
    import java.util.Collections;
    public class Test
         public static void main(String[] args)
              List ll = Collections.synchronizedList(new LinkedList());
              Object1 obj1 = new Object1();
              obj1.setS("111111");          
              ll.add(obj1);
              for (int i=0; i<ll.size(); i++)
                   Object1 obj2 = (Object1)ll.get(i);
                   System.out.println(">>>>>before:: " + obj2.getS() + "\n");
              obj1.setS("2222222");
              ll.add(obj1);
              for (int i=0; i<ll.size(); i++)
                   Object1 obj2 = (Object1)ll.get(i);
                   System.out.println(">>>>>after:: " + obj2.getS());          
    and the result looks like this:
    before:: 111111
    after:: 2222222
    after:: 2222222what i really want is something like this instead:
    before:: 111111
    after:: 111111
    after:: 2222222could any one please help
    thanks in advance
    cedricc

    You need to understand the distinction between references and objects. You're not storing objects in the linked list, but references. All of these references point to the same object. You need to create a new object each time through the loop.

  • Is an Apple ACTIVE Mini DisplayPort to Dual-Link DVI Adapter the same thing as an old Mini-DP to DVI adapter?

    Is an Apple ACTIVE Mini DisplayPort to Dual-Link DVI Adapter the same thing as an old Mini-DP to DVI adapter?
    Will a different adaptor give me better resolution between my old computer and a new monitor?
    Computer: MBP 15-inch Mid 2010
    Monitor: Dell U2713H
    Current cable: 20276 3dv ft1 DVI Digital Dual Link with a Apple Mini-DP to DVI adapter to get it to plug into my MBP.
    Possible solution?: Apple ACTIVE Mini DisplayPort to Dual-Link DVI Adapter instead of my old adapter above?

    Yes. A single-link DVI connection can't drive that monitor at its maximum resolution.
    (110544)

  • I cannot get the toggle link to the business email to stay up long enough to click it. The same thing happens when I try to hit the toggle reply "to sender" or "to all" dropdown on the side of the "reply" button. What can I do to fix this?

    Clicking on my e-mail link, [email protected], loads the business side link right underneath. I click on my e-mail address, the business side flashes on the screen, but again when I try to click it, the whole thing disappears.
    The same thing is happening with the "reply" button drop down menu for "reply to sender" and "reply to all" menu items.

    It seems like you already have an old installation of Story.
    You will have to remove it first before installing the latest one.
    So the steps would be:
    - Open 'Applications' folder in finder and move 'Adobe Story' app to Trash. Remove it from Trash too.
    - Search 'Adobe Story' in Spotlight to make sure that this application is not installed on a different drive. If installed then remove that version too.
    - Now download the latest version and install it. ( you can download the installer directly from: https://story.adobe.com/AIR/AdobeStory.air )

  • My iphone safari history, my 'reading list' shows visits and sites that I have never frequented. A few months back the same thing happened with my youtube history.  My phone is pass protected, so its just me using it. any ideas?

    My iphone safari history, my 'reading list' shows visits and sites that I have never frequented. A few months back the same thing happened with my youtube history.
    My phone is pass protected, and its just me using it, phone with me all the time. any ideas?
    How can things be added to my reading list/youtube???

    Try:                                               
    - iOS: Not responding or does not turn on           
    - Also try DFU mode after try recovery mode
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    - If not successful and you can't fully turn the iOS device fully off, let the battery fully drain. After charging for an least an hour try the above again.
    - Try another cable                     
    - Try on another computer                                                       
    - If still not successful that usually indicates a hardware problem and an appointment at the Genius Bar of an Apple store is in order.
    Apple Retail Store - Genius Bar
    The missing apps could have been done by setting the Restrictions that can hid those apps. If the backup was made with those retrictions set the the Restrictions are also restored.
    Thus, if you get it to work restore to factory settings/new iPod, not from backup                               
    You can redownload most iTunes purchases by:        
      Downloading past purchases from the App Store, iBookstore, and iTunes Store

  • When I try to access a web page or link from a web page I receive an error message like "Server not found" or "Unable to connect." After repeated "try again" attempts the page will load, but when I click on a button or link, the same thing repeats. Why?

    When I try to access any web page or any link from a web page, I receive an error message such as "Server not found" or "Unable to connect." After repeated "try again" attempts that the page will load, but as soon as I click on a button or link, the same thing repeats. Any suggestions?

    When I try to access any web page or any link from a web page, I receive an error message such as "Server not found" or "Unable to connect." After repeated "try again" attempts that the page will load, but as soon as I click on a button or link, the same thing repeats. Any suggestions?

  • Me and my dad share an iTunes account and all of his music he has purchased on ITunes shows up on my songs list with a cloud icon next to it. How do I get rid of these from my songs list? Cuz it's doing the same thing on my iPhone

    Me and my dad share an iTunes account and all of his music he has purchased on ITunes shows up on my songs list with a cloud icon next to it. How do I get rid of these from my songs list? Cuz it's doing the same thing on my iPhone.

    Go to Edit > Preferences > Store, and uncheck the box for "Show iTunes in the Cloud purchases."

  • Hello! I use the VSCO preset that was easy to download and use right away a few months ago. This morning I did the same thing and it downloaded successfully but none of the presets are listed under the new VSCO folder I bought. How can I fix this? Does Li

    Hello! I use the VSCO preset that was easy to download and use right away a few months ago. This morning I did the same thing and it downloaded successfully but none of the presets are listed under the new VSCO folder I bought. How can I fix this? Does Lightroom have a limit on presets?

    Hello! I use the VSCO preset that was easy to download and use right away a few months ago. This morning I did the same thing and it downloaded successfully but none of the presets are listed under the new VSCO folder I bought. How can I fix this? Does Lightroom have a limit on presets?

  • Help needed in linked lists...

    I have been working on this computer assignment lately but I still don't understand linked lists yet..I did an assignment on array based implementation and now I am supposed to do the same thing in linked list implementation..
    I need help on how to change this into a linked list implementation..any help would be appreciated. Thank you..below is the code for the array based implementation..the only thing that needs change here is after where is says Array-based implementation of the ADT list.
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Array-based implementation of the ADT list.
    class ListArrayBased {
        private static final int MAX_LIST = 50;
        private Object items[];  // an array of list items
        private int numItems;  // number of items in list
        public ListArrayBased()
        // creates an empty list
             items = new Object[MAX_LIST];
             numItems = 0;
        }  // end default constructor
        public boolean isEmpty()
          return (numItems == 0);
        } // end isEmpty
        public int size()
           return numItems;
        }  // end size
        public void removeAll()
          // Creates a new array; marks old array for
          // garbage collection.
          items = new Object[MAX_LIST];
          numItems = 0;
        } // end removeAll
        public void add(int index, Object item) throws  ListIndexOutOfBoundsException
          if (numItems > MAX_LIST)
            throw new ListException("ListException on add");
        }  // end if
          if (index >= 1 && index <= numItems+1)
            // make room for new element by shifting all items at
            // positions >= index toward the end of the
            // list (no shift if index == numItems+1)
            for (int pos = numItems; pos >= index; pos--) {
              items[translate(pos+1)] = items[translate(pos)];
          } // end for
          // insert new item
          items[translate(index)] = item;
          numItems++;
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
             "ListIndexOutOfBoundsException on add");
          }  // end if
        } //end add
        public Object get(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            return items[translate(index)];
          else 
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
              "ListIndexOutOfBoundsException on get");
          }  // end if
        } // end get
        public void remove(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            // delete item by shifting all items at
            // positions > index toward the beginning of the list
            // (no shift if index == size)
                for (int pos = index+1; pos <= size(); pos++) {
                    items[translate(pos-1)] = items[translate(pos)];
          }  // end for
          numItems--;    
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException("ListIndexOutOfBoundsException on remove");
          }  // end if
        } // end remove
        private int translate(int position) {
        return position - 1;
       } // end translate
    }  // end ListArrayBased
    class ListException extends RuntimeException
      public ListException(String s)
        super(s);
      }  // end constructor
    }  // end ListException
    class ListIndexOutOfBoundsException
                extends IndexOutOfBoundsException {
      public ListIndexOutOfBoundsException(String s) {
        super(s);
      }  // end constructor
    }  // end ListIndexOutOfBoundsException

    Could someone check for me if this will work and if it doesn't what I need to do to make it work..Thanks...
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Linked List-based implementation of the ADT list.
    class ListNode
         //class to represent one node in a list
         class ListNode
              //package access members; List can access these directly
              Object data;
              ListNode nextNode;
              //contructor creates a ListNode that refers to object
              ListNode( Object object)
                   this( object, null );
              } //end ListNode one-argument constructor
              //constructor creates ListNode that refers to
              // Object and to the next ListNode
              ListNode ( Object object, ListNode node)
                   data = object;
                   nextNode = node;
              // end ListNode two-argument contructor
              //return reference to data in node
              Object getObject()
                   return data; // return Object in this mode
              //return reference to next node in list
              ListNode getNext()
                   return nextNode; // get next node
              } // end method getNext
    } //end class ListNode
    //class List Definition
    public class List
         private ListNode firstNode;
         private ListNode lastNode;
         private String name; // string like " list " used in printing
         //contructor creates empty List with " list " as the name
         public List()
              this(" list ");
         } //end List no-arguement constructor
    //contructor creates an empty list with a name
    public List( String listName )
         name = listname;
         firstNode = lastNode = null;
    } //end List no-arguement contructor
    //insert Object at front of List
    public void insertAtFront ( object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = lastNode = newListNode( insertItem );
         else // firstNode refers to new node
              firstNode = new ListNode ( insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insert AtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = new ListNode ( insertItem );
         else // firstNode refers to new node
         firstNode = new ListNode (insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insertAtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and LastNode refer to same Object
              firstNode = lastNode = new ListNode ( insertItem );
         else // lastNode = lastNode.nextNode = new ListNode ( insertItem );
    } // end method insertAtBack
    //remove first node from List
    public Object removeFromFront() throws EmptyListException
         if( isEmpty() ) //throw exception if list is empty
         throw new EmptyListException( name );
         object removedItem = firstNode.data; //retrieve data being removed
    // update references firstNode and lastNode
    if (firstNode == lastNode )
         firstNode =lastNode = null;
    else
         firstNode = firstNode.nextNode;
         return removedItem; // return removed node data
    } //end method removeFromFront
    //remove last node from List
    Public Object removeFromBack() throws EmptyListException
         If ( isEmpty() ) // throw exception if list is empty
              throw new EmptyListException( name );
         Object removedItem = lastNode.data; // retrieve data being removed
         // update references firstNode and lastNode
         If ( firstNode == lastNode )
              firstNode = lastNode = null;
         else // locate new last node
              ListNode current = firstNode;
              // loop while current node does not refer to lastNode
              while ( current.nextNode != lastNode )
                   current = current.nextNode;
              lastNode = current; // current is new lastNode
              current.nextNode = null;
         } // end else
         return removedItem; // return removed node data
    } // end method removeFromBack
    // determine whether list is empty
    public boolean isEmpty()
         return firstNode == null; // return true if list is empty
    }     // end method isEmpty
    //output List contents
    public void print()
         if (isEmpty() )
              System.out.printf(�Empty %s\n�, name );
              return;
         System.out.printf(�The %s is: �, name );
         ListNode current = firstNode;
         //while (current != null )
              System.out,printf(�%s �, current.data );
              current = current.nextNode;
         } //end while
         System.out.println( �\n� );
    } //end method print
    } end class List

  • Alphabetizing a linked list, HELP!

    To all:
    Firstly, I'm not looking for someone to do my assignment for me. I just need a push in the right direction...
    I need to create a linked list that contains nodes of a single string (a first name), but that list needs to be alphabetized and that's where I am stuck.
    I can use an iterator method that will display a plain-old "make a new node the head" linked list with no problem. But I'm under the impression that an iterator method is also the way to go in alphabetizing this list (that is using an iterative method to determine the correct place to place a new node in the linked list). And I am having zero luck doing that.
    The iterator method looks something like this:
    // ---- MyList: DisplayList method ----
    void DisplayList()
    ListNode p;
    for (ResetIterator(); (p = Iterate()) != null; )
    p.DisplayNode();
    // ---- MyList: ResetIterator method ----
    void ResetIterator()
    current = head;
    // ---- MyList: Iterate method ----
    ListNode Iterate()
    if (current != null)
    current = current.next;
    return current;
    Can I use the same iterator method to both display the final linked list AND alphabetize my linked list or do I need to create a whole new iterator method, one for each?
    Please, someone give me a hint where to go with this. I've spent something like 15 hours so far trying to figure this thing out and I'm just stuck.
    Thanks so much,
    John
    [email protected]

    I'll try and point you in the right direction without being too explicit as you request.
    Is your "linked list" an instance of the Java class java.util.LinkedList or a class of your own?
    If it is the Java class, then check out some of the other types of Collections that provide built-in sorting. You should be able to easily convert from your List to another type of Collection and back again to implement the sorting. (hint: you can do this in two lines of code).
    If this is your own class and you want to code the sort yourself, implement something simple such as a bubble sort (should be easy to research on the web).
    Converting to an array, sorting that and converting back is another option.
    Good Luck.

  • A linked list question.

    So, I believe I understand linked lists for the most part, except for two lines....
        boolean add(Transaction item)
            for (Transaction curr = first; curr != null; curr = curr.next)
                if (curr.part_num == item.part_num)
                    return false;
            Transaction newItem = new Transaction();
            newItem.transcode = item.transcode;
            newItem.description = item.description;
            newItem.part_num = item.part_num;
            newItem.quantity = item.quantity;
            newItem.next = first;
            first.next = newItem;
            return true;
        }first is null, so First.next would be the first available space for actual insertion, and this is why it then puts null as newItem.next (the end of the list), and sticks newItem in first.next?
    Im glad I read that pass by value thing earlier at the Java Ranch place...
    Heres my actual question: When newItem.next = first; is called, it just copies null as the next field, but leaves the null in first alone right? And then it takes first.next and makes newItem copy into that field, thus inserting the first real item in the list?
    Please tell me I made that connection right. :-D
    Thanks!!

    Pictures are worth a hundred words with linked lists. Did you even put a pencil and paper next to your computer while doing this program, so that you could draw what is happening when you get confused?
    If first is null, then the for loop is skipped--because first is assigned to curr and the loop only executes when curr is not equal to null.
    So, this happens:
    newItem = new Transaction()
    int Transcode = 0
    String description = null
    int partNumber = 0
    int quantity = 0
    Tranasaction next = nullThen values are assigned to each field:
    newItem
    int Transcode = 10
    String description = "screw"
    int partNumber = 46
    int quantity = 200
    //freeze execution here:
    Tranasaction next = null (what will happen here??)Your assumption was:
    Transaction first = null
    That means first does not refer to a Transaction object. Therefore, first does not have a description member, a quantity member, etc., and this is what things look like just before newItem.next = first; is executed:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ------> nullNow,
    When newItem.next = first; is calledthings change to this:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
          /-------Tranasaction next
    first ------> null That isn't what you want. When you add() a Transaction object to the end of your linked list, it's next member should be null. It's the end of the chain, so there is no next.
    And then it takes first.next and makes newItem copy
    into that field, thus inserting the first real item in the
    list?No. first is null so it does not refer to a Transaction object, and therefore there is no next member variable and consequently no such thing as first.next. You need to understand that null and a Transaction object that has 0 for every member are not the same.
    But suppose for a minute that null and a Transaction object with zeros for every field were the same thing, so that first.next existed. If that was the case, then you could assign newItem to first.next. But, then you would be left with this:
    first
    int Transcode = 0
    String description = null
    int partNumber = 0
    int quantity = 0
    Tranasaction next = newItemWould you want the first Transaction object in your LinkedList to be almost entirely empty?
    Instead, if first is null, you want to make first refer to newItem, i.e. you want to do this:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ----/   nullThen when the add() method ends, since newItem is a local variable, it will be destroyed leaving you with this:
                  Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ----/   null

  • Linked List and String Resources

    Linked Lists can be very slow when removing dynamic Strings.
    If you add and remove Strings in the
    following way, the performance is very poor:
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    - If you add and remove the not dynamic String: "" + 10000 instead,
    - or do not remove the String (but add it in the middle),
    - or use a ArrayList
    the performance is much better.
    I suppose it depends on handling the String resources.
    If you run the following class, you will see what I mean:
    public class SlowLinkedList
    public static void main (String[] args)
    // Be carefull when accessing/removing Strings in a Linked List.
    testLinkedList ();
    testLinkedListHardCodedString();
    testLinkedListNoRemove();
    testArrayList();
    testArrayListNoParam();
    private static void testLinkedList ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time dynamic String remove " + time);
    private static void testLinkedListHardCodedString ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + 10000);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time same String remove " + time);
    private static void testLinkedListNoRemove ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add (i/2, "" + n);
    time = System.currentTimeMillis () - time;
    System.out.println ("time add dynamic String " + time);
    private static void testArrayList ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new ArrayList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time ArrayList " + time);
    private static void testArrayListNoParam ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new ArrayList ();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + 10000);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time ArrayList same String " + time);
    A typic output of the Performance is:
    time dynamic String remove 1938
    time same String remove 312
    time add dynamic String 31
    time ArrayList 63
    time ArrayList same String 31

    begin long winded reply
    It doesn't matter if they are Strings or any other Object. LinkedList, in the way you are executing
    remove, is not effecient. The LinkList remove will look at the index, if it is less than the median
    it will start iterating from 0, if it is greater, it will start iterating in reverse from the end. Since you
    are removing from the median, it will always take the longest (either forward or backward) to
    get to the middle. Whereas, ArrayList simply uses the arraycopy to drop the element from the
    array. The "NoRemove" test doesn't make sense to me in relation to the others.
    Also, the VM is performing optimizations when you hardcode the 'n' value to 10000, it seems
    that the VM won't optimize when using 'n'. Tusing Integer.toString(n), instead of "" + n,
    in the first test case, it will yield better results.
    My profs in college drove collections into my head and removing from a linked list without
    an iterator is going to be inefficient. Iterators are a beautiful thing, use them.
    Try this code instead, it simulates your remove in the middle with an iterator and, on my
    machine, is faster than the ArrayList.
    private static void testLinkedList() {
        int n = 10000;
        long time = System.currentTimeMillis ();
        List list = new LinkedList();
        for (int i = 0 ; i < n ; i++) {
            list.add (Integer.toString(n));
        boolean forward = false;
        for (ListIterator li = list.listIterator(n >> 1); li.hasNext() || li.hasPrevious();) {
            if (forward) {
                li.next();
                forward = false;
            } else {
                li.previous();
                forward = true;
            li.remove();
        time = System.currentTimeMillis () - time;
        System.out.println ("time dynamic String remove " + time);
    }One other thing, run the tests more than once in a single VM and take the average. You could
    apply some statistical analysis to figure out which is better within a certain confidence percentage,
    but that is probably overkill. :)
    Check the collection tutorial for more info: http://java.sun.com/docs/books/tutorial/collections/implementations/general.html
    end long winded reply
    Matt

  • Linked lists problem -- help needed

    Hello again. I've got yet another problem in my C++ course that stems from my use of a Mac instead of Windows. I'm going to install Parallels so I can get Windows on my MacBook and install Visual Studio this week so that I don't have to deal with these discrepancies anymore, but in the meanwhile, I'm having a problem here that I don't know how to resolve. To be clear, I've spent a lot of time trying to work this out myself, so I'm not just throwing this up here to have you guys do the work for me -- I'm really stuck here, and am coming here as a last resort, so I'll be very, very appreciative for any help that anyone can offer.
    In my C++ course, we are on a chapter about linked lists, and the professor has given us a template to make the linked lists work. It comes in three files (a header, a source file, and a main source file). I've made some adjustments -- the original files the professor provided brought up 36 errors and a handful of warnings, but I altered the #include directives and got it down to 2 errors. The problematic part of the code (the part that contains the two errors) is in one of the function definitions, print_list(), in the source file. That function definition is shown below, and I've marked the two statements that have the errors using comments that say exactly what the errors say in my Xcode window under those two statements. If you want to see the entire template, I've pasted the full code from all three files at the bottom of this post, but for now, here is the function definition (in the source file) that contains the part of the code with the errors:
    void LinkedList::printlist( )
    // good for only a few nodes in a list
    if(isEmpty() == 1)
    cout << "No nodes to display" << endl;
    return;
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->name; } cout << endl; // error: 'setw' was not declared in this scope
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->test_grade; } cout << endl; // error: 'setw' was not declared in this scope
    As you can see, the problem is with the two statements that contain the 'setw' function. Can anyone help me figure out how to get this template working and get by these two errors? I don't know enough about linked lists to know what I can and can't mess with here to get it working. The professor recommended that I try using 'printf' instead of 'cout' for those two statements, but I don't know how to achieve the same effect (how to do whatever 'setw' does) using 'printf'. Can anyone please help me get this template working? Thank you very, very much.
    For reference, here is the full code from all three files that make up the template:
    linkedlist.h (header file):
    #ifndef LINKED_LINKED_H
    #define LINKED_LINKED_H
    struct NODE
    string name;
    int test_grade;
    NODE * link;
    class Linked_List
    public:
    Linked_List();
    void insert(string n, int score);
    void remove(string target);
    void print_list();
    private:
    bool isEmpty();
    NODE *FRONT_ptr, *REAR_ptr, *CURSOR, *INSERT, *PREVIOUS_ptr;
    #endif
    linkedlist.cpp (source file):
    #include <iostream>
    using namespace std;
    #include "linkedlist.h"
    LinkedList::LinkedList()
    FRONT_ptr = NULL;
    REAR_ptr = NULL;
    PREVIOUS_ptr = NULL;
    CURSOR = NULL;
    void Linked_List::insert(string n, int score)
    INSERT = new NODE;
    if(isEmpty()) // first item in List
    // collect information into INSERT NODE
    INSERT-> name = n;
    // must use strcpy to assign strings
    INSERT -> test_grade = score;
    INSERT -> link = NULL;
    FRONT_ptr = INSERT;
    REAR_ptr = INSERT;
    else // else what?? When would this happen??
    // collect information into INSERT NODE
    INSERT-> name = n; // must use strcpy to assign strings
    INSERT -> test_grade = score;
    REAR_ptr -> link = INSERT;
    INSERT -> link = NULL;
    REAR_ptr = INSERT;
    void LinkedList::printlist( )
    // good for only a few nodes in a list
    if(isEmpty() == 1)
    cout << "No nodes to display" << endl;
    return;
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->name; } cout << endl; // error: 'setw' was not declared in this scope
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->test_grade; } cout << endl; // error: 'setw' was not declared in this scope
    void Linked_List::remove(string target)
    // 3 possible places that NODES can be removed from in the Linked List
    // FRONT
    // MIDDLE
    // REAR
    // all 3 condition need to be covered and coded
    // use Trasversing to find TARGET
    PREVIOUS_ptr = NULL;
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    if(CURSOR->name == target) // match
    { break; } // function will still continue, CURSOR will
    // mark NODE to be removed
    else
    { PREVIOUS_ptr = CURSOR; } // PREVIOUS marks what NODE CURSOR is marking
    // JUST before CURSOR is about to move to the next NODE
    if(CURSOR == NULL) // never found a match
    { return; }
    else
    // check each condition FRONT, REAR and MIDDLE
    if(CURSOR == FRONT_ptr)
    // TARGET node was the first in the list
    FRONT_ptr = FRONT_ptr -> link; // moves FRONT_ptr up one node
    delete CURSOR; // deletes and return NODE back to free memory!!!
    return;
    }// why no need for PREVIOUS??
    else if (CURSOR == REAR_ptr) // TARGET node was the last in the list
    { // will need PREVIOUS for this one
    PREVIOUS_ptr -> link = NULL; // since this node will become the last in the list
    REAR_ptr = PREVIOUS_ptr; // = REAR_ptr; // moves REAR_ptr into correct position in list
    delete CURSOR; // deletes and return NODE back to free memory!!!
    return;
    else // TARGET node was the middle of the list
    { // will need PREVIOUS also for this one
    PREVIOUS_ptr -> link = CURSOR-> link; // moves PREV nodes' link to point where CURSOR nodes' points
    delete CURSOR; // deletes and return NODE back to free memory!!!
    return;
    bool Linked_List::isEmpty()
    if ((FRONT_ptr == NULL) && (REAR_ptr == NULL))
    { return true; }
    else
    { return false;}
    llmain.cpp (main source file):
    #include <iostream>
    #include <string>
    #include <iomanip>
    using namespace std;
    #include "linkedlist.h"
    int main()
    Linked_List one;
    one.insert("Angela", 261);
    one.insert("Jack", 20);
    one.insert("Peter", 120);
    one.insert("Chris", 270);
    one.print_list();
    one.remove("Jack");
    one.print_list();
    one.remove("Angela");
    one.print_list();
    one.remove("Chris");
    one.print_list();
    return 0;

    setw is the equivalent of the field width value in printf. In your code, the printf version would look like:
    printf("%8s", CURSOR->name.c_str());
    I much prefer printf over any I/O formatting in C++. See the printf man page for more information. I recommend using Bwana: http://www.bruji.com/bwana/
    I do think it is a good idea to verify your code on the platform it will be tested against. That means Visual Studio. However, you don't want to use Visual Studio. As you have found out, it gets people into too many bad habits. Linux is much the same way. Both development platforms are designed to build anything, whether or not it is syntactically correct. Both GNU and Microsoft have a long history of changing the language standards just to suit themselves.
    I don't know what level you are in the class, but I have a few tips for you. I'll phrase them so that they answers are a good exercise for the student
    * Look into const-correctness.
    * You don't need to compare a bool to 1. You can just use bool. Plus, any integer or pointer type has an implicit cast to bool.
    * Don't reuse your CURSOR pointer as a temporary index. Create a new pointer inside the for loop.
    * In C++, a struct is the same thing as a class, with all of its members public by default. You can create constructors and member functions in a struct.
    * Optimize your function arguments. Pass by const reference instead of by copy. You will need to use pass by copy at a later date, but don't worry about that now.
    * Look into initializer lists.
    * In C++ NULL and 0 are always the same.
    * Return the result of an expression instead of true or false. Technically this isn't officially Return Value Optimization, but it is a good habit.
    Of course, get it running first, then make it fancy.

Maybe you are looking for

  • How do I sync Notes between my iPad and iPhone?

    My Notes on my ipad are not syncing with the notes on my iPhone. Aren't they supposed to sync?

  • UDF's and XSLT Mapping

    Hi,      I am very much confused when to use UDF's and when to use XSLT etc. Please make me to understand with good examples.

  • Low broadband speed starting from this morning

    Hi! I can normally get 7-7.5Mbps from my broadband connection. This morning, the speed dropped dramatically to 1.85 Mbps. Here is my HomeHub ADSL values: ADSL line status Connection information Line state Connected Connection time 0 days, 2:30:38 Dow

  • How close acrobat (with a batch)

    Hello, I'm trying to close Adobe Reader in vbscript after having print a pdf document. How can I achieve this ? Many thanks for your help.

  • Dynamic vlan assignment with openldap

    Hi, I have a scenario where my customer has an ACS 5.2 and couple WLCs. the customer has also a openldap database and needs to do dynamic vlan assignement for his wireless user against this database. I know that for Active directory it works, please