LinkedList && ArrayList &&  gc

I have implemented Stack by LinkedList and ArrayList.
In theory, when many additions and deletions on stack(I test stack in 10000000 operations), the LinkedList should have better peformance than ArrayList. But the result is that ArrayList is better performance.
Finally, I think the major reason is the gc's behaviors we can not expected. The performances of two implementions for stacks are very in stable. But lone time seeing, the result is ArrayList's then LinkedList's.

The relative performance depends on how deep the stack
gets. If it stays approximately the same depth all the
time then the ArrayList won't have to resize its array
whereas a LinkedList always creates a new wrapper
object for each inserted element. If the stack gets
very deep then the ArrayList would have to resize the
array every time it overflows and that is quite slow
and memory consuming.No, the ArrayList wouldn't have to resize the array
often. It grows by 50% each time, so would in fact
resize less often as it gets bigger. I'm not sure what
you mean about "every time it overflows".An ArrayList (well, actually the underlying array that it uses) overflows when you add an element to it when its underlying array is full. When it overflows the underlying array is resized to 150% (more specifically: to Ceil(150%)).
If the stack once in its lifetime gets very deep it results in a lot of resizes (as I said, every time it overflows), each time using 250% of the amount of memory needed, and causing an arraycopy of 100% of the memory in use.
This happens only when the stack gets deeper for the first time, which is both good and bad. The good thing is that it happens only when the array gets larger than it has ever been before. The bad thing is that if the array shrinks a lot (and remains small) most of the large array remains unused. (Of course you can trimToSize() manually, but then you'd have to know when to do that.)
I would create a hybrid of those: a linked list containing arrays. That way there wouldn't be any arraycopying (and thus the peak memory usage can be kept low) and unused arrays could be garbage collected. There are several ways to do this, which one is The Right Way™ depends on the situation.
- Marcus

Similar Messages

  • Partial Interface Implementation.....am I right?

    Hi there everyone,
    I am reading Ivor Hortons book, "Beginning Java 2 SDK 1.4 Edition". I have just got to the part where he talks about interfaces. I get interfaces, no problem.....but then he goes on about implementing some methods from an interface and not others. I quote: -
    "You can omit the implementation of one or more of the methods from the interface in a class that implements the interface, but in this case the class inherits some abstract methods from the interface so we would need to declare the class itself as abstract"
    This is what I think he means (from what I have learned so far)....
    An abstract class is a class that that declares methods without actually "filling them in"....it is assumed that this will be done by a sub-class which inherits from this super-class.
    Therefore, if you don't implement all the methods in the interface in a class, that class must also be declared as abstract, as you have methods left over that you have not implemented.
    Is this right?
    He goes on to say that because the class is an abstract class, you can't create instances of this class....unless a sub-class of this class is created that implements the remaining methods. Which seems logical, I guess.....but why would you do this? It seems to be a lot of trouble just to neglect a few methods...they have to be implemented in a sub-class anyway to "arrive at a useful class" as he puts it.
    So whats the point?
    Also (as an aside)....if you have a class that must enforce method formatting.....why would you use an interface instead of having your class inherit abstract methods from a super-class? Is is because you can only inherit from one super-class (which wouldn't be much use for sub-classes that needed to enforce certain other methods)? I understand that C++ can inherit from multiple super-classes, thus negating the need for interfaces. This seems right to me.
    How did I do? :) Any comments?
    Thank you.
    Jon

    An abstract class is a class that that declares
    methods without actually "filling them in"....
    etc....
    Is this right?Pretty much, yep.
    He goes on to say that because the class is an
    abstract class, you can't create instances of this
    class....unless a sub-class of this class is created
    that implements the remaining methods. Which seems
    logical, I guess.....but why would you do this? It
    seems to be a lot of trouble just to neglect a few
    methods...they have to be implemented in a sub-class
    anyway to "arrive at a useful class" as he puts it.
    So whats the point?When you specify the interace, let's call it Foo, you're saying what methods a class must provide if it's to call itself a Foo, but not how do provide that funcionality--that's left up to the actual implementation, as you've learned. For a given interface, there are many ways it could be implemented. However, there may be some common implementations for some of the methods that a family of implementing classes can share--a default implementation that isn't tuned and tweaked for any particular kind of use, but that does work. There may also be some methods for which no reasonable default exists, because it would be too closely tied to whatever your particular implementation is.
    For a good example of this, look at the Collections Framework in the java.util package: List, AbstractList, AbstractSequentialList, LinkedList, ArrayList. By the time you get down to either LinkedList or ArrayList, there are only a couple of methods that are left unimplemented. Those methods interact directly with the backing store--i.e. that have to access "array[ix]" for ArrayList or the linked list nodes for LinkedList, so it doesn't make sense to provide a "common" or "default" implementation. The other methods use these methods to do their work, so they don't depend on the particulars of the backing store and hence a common/default implementation is provided for them.

  • Implementing Lists

    I am at the point where I have had two Java courses and am now ready to learn data structures. I have a book and it is ok, but it does not show you any implementation of the data structrues. Right now I am starting with the most basic data structure which is Lists and i understand how they work (array based, Linked-List and Double-Linked-Lists) however the book shows no implementation of them in "main". If someone could point me to some resources that show these implementations, I would greatly appreciate it.

    Have a look in the src.zip file which comes with your JDK. It has the source for 90+% of the Java APIs including List, LinkedList, ArrayList, CopyOnWriteArrayList.
    You can also find copies of the source posted on the web.

  • How to use lists or vectors and things?

    Hello !
    I started to code with java about year ago and the first jdk that i used was 1.5.0. Since 1.5.0, generics have been supported and I think that linkedlists, arraylists and whatever have been made differently. I can't use these generics in my mobile applications so I don't how to use vectors and stacks etc, different way in my applications.
    When I used (for instance) arrayists with jdk 1.5.0 or 6, I did it like this:
    ArrayList <AL> al = new ArrayList <AL>();
    void something(){
    for(AL a : al){
    //do something
    But how do I do these with mobile things, and whats the most similar thing compared to linkedlist and arraylist, vector? I really don't know how to add and remove things with these. If someone can point a good tutorial or thread, I would really appreciate that.
    Edited by: RandomNero, for a third time in a row, on Dec 13, 2007 1:42 PM

    Hello,
    there's no typed vectors on J2ME,
    please check out this link : http://java.sun.com/javame/reference/apis/jsr118/java/util/Vector.html
    to know more about J2ME vectors.

  • How to keep track of an iterator?

    Hi everyone.
    I'm having an issue trying to keep track of an interator in a tree map.
    Basically my application is an address book, and it has the following button:
    First Prev Next Last
    So if they press the first button it will run the following code:
      Collection c = treeMap.values();
            //obtain iterator for tree map
            Iterator iter = c.iterator();
            //get first item in the list
            Contact temp = (Contact)iter.next();This works fine.
    But now I'm trying to get the Last element in the tree and then assign a "global" iterator to it, infact all the buttons should have an iterator that will keep track of where the current element is...and thats where I'm having problems with.
    So if I get the first element when someone presses the first button, I would like to now assign an iterator to that position, so if someone presses the Next button, I would just do iter.next(); and then display the information .
    The problem is though, I also need to go back 1 element if the user presses the Previous button...is there a way to go forward and backward with an iterator?
    I have an internal iterator keeping track of things but I get an error, like for example:
      Collection c = treeMap.values();
             int count = 0;
            //obtain iterator for tree map
            Iterator iter = c.iterator();
            while(iter.hasNext() && count < treeMap.size()-1)
                count++;
                iter.next();
            trackIter = iter.next();trackIter = iter.next();
    I want trackIter to point to whatever iter.next() is pointing at, which in this case, is the last element in the list but I get an error here saying:
    found : java.lang.Object
    required: java.util.Iterator
    trackIter = iter.next();
    Any ideas?
    Thanks

    First of all your bug.
    Iterators return Objects.
    What kind of object it returns depends on what you were shoving into the Map. If you shoved a Dog into the map, then the iterator returns the Dog, but the Iterator and the Collection only knows that it is an Object, not that it is a Dog. Your code that needed to get a Dog back, needs to cast the result returned by the iterator as a Dog
    trackItem = (Dog) iter.next();
    However, before you haul off and fix your code, twould be best to fix your design. Your question, "is there a way to go forward and backward with an iterator?" is a good question. Before I tell you the answer, let me ask you a question? What are you going to do if the answer is "NO - you can't go forward and backward"
    I mean, it's OK to hack and slash around, trying this and that, but generally it would be good to know the answer to that question BEFORE you write a bunch of code involving iterators, because when you find out that you CAN'T go both forward and backwards with an iterator, what are you gonna do. Are you going to leave part of the design working one way, using iterators for going next and then some totally different mechanism to go the other way? Of course you could do that, but that is not really how one arrives at good design, by first hacking out one feature until you can get it working and then turning you attention to the next and hacking out a different bunch of code.
    Observe that Collections can be converted to Arrays and that Arrays have indicies and moving forward and backward in an array is a simple matter of incrementing or decrementing an integer and testing if you fell of the end. Also arrays, having no particular order restrictions can be sorted, or re-ordered any way that you like. How much easier your problem would be if only you had an array instead of a Collection.
    Don't take the criticism of your design the wrong way. I actually like the idea of using something like an iterator for your buttons, but the thing you are using is not really an iterator. As you said it must go both ways. It is really more like a text cursor where you can advance forward and backwards over a list. So build a Cursor class that you can hand an array. Give it routines like, first(), last(), mid(), stepForward(), stepBack(), getCurrent(), getIndex(), setIndex().
    And then you ask yourself, "before I write this code - let me see if someone has already written it." you look up Cursor in the API. Nope, there is a cursor class, but it is for crossHair cursors and the like. Then you ask yourself, "What else could they have called this?" How about ListIterator. Bingo - there you are, an interface class that has hasNext, hasPrevious, ... But it is only an interface. It doesn't do anything. What kind of class would implement this interface? Maybe List, so you look up List. Drat, it is some disgusting awt component. Oh wait, there's another interface, List, and there on the "All known Implementing Classes" you see LinkedList, ArrayList and others.
    Cool. You can reduce a collection to an array, if you could get an array into one of these list types, you could have your interface all built for you and everything, or if it isn't exactly what you want, no big deal, you already know the interface you need, you can just build it, whatever reduces your effort.
    See how it works? And just for the record, I didn't know about ListIterators, when I started typing this. But I know a design principle that helped me find it. I don't grab a component that I know and see if I can make the system work with the thing that I know. Instead I think of what I want it to do, try to design the interface for what I want it to do and then, once I know what I want from a structural standpoint, I start groveling around to see if that thing already exists.
    You were almost there. When you asked if an Iterator goes both forwards and backwards. And the answer is, "No"
    I see that others have posted before I finished writing this tome. Reversing the array and creating an iterator for that list will not get you the behavior that you are in some state, at some place in the list, from which you can go either forward or backwards. It just gets you a way to go backwards through the list.
    On the assumption that you are a student attempting to learn something, I would suggest that you actually do both approaches. Using the ListIterator approach is what you would do in a production environment (I just need this one behavior and it already exists over here) but you will probably learn more if you implement your own cursor class as I described above. The point is that you have a chunk of functionality, knowing where you are in a list and being able to step either forward or backward, that you want to achieve. The way that you get some chunk of functionality is that you design and build a class that lets you get that functionality. Iterator is NOT that class.

  • THIS IS A REALLY HARD ONE

    Hi, this is a really hard one but here I go. Well the code below takes in an array of cards(playing cards) and finds all possible subsets of the array. These subsets are stored in separate arrays and then each array is mapped to a key and stored in a linklist. Later for a given key on of the subset arrays is exported to the method that passed that called it.
    import java.io.*;
    import java.util.*;
    public class Subsets {
         Properties ht = new Properties();
         LinkedList ll = new LinkedList();
         ArrayList al1, al2, al3, al4, al5, al6, al7, al8;
         String           key = null;
         String           key2;
         int          intKey;
    ArrayList newArr = null;
    public ArrayList permutations(Hand dk, Hand comp){
         for (int f=0; f < dk.getCardCount(); f++){
              key = String.valueOf(dk.getCard(f).getValue());
              al1 = new ArrayList();
              al1.add(dk.getCard(f));
              ll.add(ht.put(key,al1));
              for (int s=f+1; s < dk.getCardCount(); s++){
                   key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue());
                   al2 = new ArrayList();
                   al2.add(dk.getCard(f));
                   al2.add(dk.getCard(s));
                   ll.add(ht.put(key, al2));
                   //v.addElement(ht.put(key,cd2));
                   for (int t=s+1; t < dk.getCardCount(); t++){
                        key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue());
                        al3 = new ArrayList();
                        al3.add(dk.getCard(f));
                        al3.add(dk.getCard(s));
                        al3.add(dk.getCard(t));
                        ll.add(ht.put(key,al3));
                        //v.addElement(ht.put(key,cd3));
                        for (int a=t+1; a < dk.getCardCount(); a++){
                             key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue());
                             al4 = new ArrayList();
                             al4.add(dk.getCard(f));
                             al4.add(dk.getCard(s));
                             al4.add(dk.getCard(t));
                             al4.add(dk.getCard(a));
                             ll.add(ht.put(key,al4));
                             for (int b=a+1; b < dk.getCardCount(); b++){
                                  key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue()+dk.getCard(b).getValue());
                                  al5 = new ArrayList();
                                  al5.add(dk.getCard(f));
                                  al5.add(dk.getCard(s));
                                  al5.add(dk.getCard(t));
                                  al5.add(dk.getCard(a));
                                  al5.add(dk.getCard(b));
                                  ll.add(ht.put(key,al5));
                                                      for (int c=b+1; c < dk.getCardCount(); c++){
                                       key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue()+dk.getCard(b).getValue()+dk.getCard(c).getValue());
                                       al6 = new ArrayList();
                                       al6.add(dk.getCard(f));
                                       al6.add(dk.getCard(s));
                                       al6.add(dk.getCard(t));
                                       al6.add(dk.getCard(a));
                                       al6.add(dk.getCard(b));
                                       al6.add(dk.getCard(c));
                                       ll.add(ht.put(key,al6));
                                       //v.addElement(ht.put(key,cd6));
                                       for (int d=c+1; d < dk.getCardCount(); d++){
                                            key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue()+dk.getCard(b).getValue()+dk.getCard(c).getValue()+dk.getCard(d).getValue());
                                            al7 = new ArrayList();
                                            al7.add(dk.getCard(f));
                                            al7.add(dk.getCard(s));
                                            al7.add(dk.getCard(t));
                                            al7.add(dk.getCard(a));
                                            al7.add(dk.getCard(b));
                                            al7.add(dk.getCard(c));
                                            al7.add(dk.getCard(d));
                                            ll.add(ht.put(key,al7));
                                            //v.addElement(ht.put(key,cd7));
                                            for (int e=d+1; e < dk.getCardCount(); e++){
                                                 key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue()+dk.getCard(b).getValue()+dk.getCard(c).getValue()+dk.getCard(d).getValue()+dk.getCard(e).getValue());
                                                 al8 = new ArrayList();
                                                 al8.add(dk.getCard(f));
                                                 al8.add(dk.getCard(s));
                                                 al8.add(dk.getCard(t));
                                                 al8.add(dk.getCard(a));
                                                 al8.add(dk.getCard(b));
                                                 al8.add(dk.getCard(c));
                                                 al8.add(dk.getCard(d));
                                                 al8.add(dk.getCard(e));
                                                 ll.add(ht.put(key,al8));
         Iterator itr = ll.iterator();
         first:{
              while(itr.hasNext()){     
                        key2 = String.valueOf(itr.next());
                        intKey = Integer.parseInt(key2);
                   for(int j=comp.getCardCount()-1; j<=0;j++){
                        if(intKey == comp.getCard(j).getValue()){
                             newArr = (ArrayList)ht.get(key2);
                             break first;
              if(!itr.hasNext()){
                   newArr = null;
         return newArr;
    the snippit of code below below is what called the code above.
    if(cardsOnTable.getCardCount() == 0){
    System.out.println(COMPUTER_name+" discards the " + COMPUTER_player.getCard(COMPUTER_player.getCardCount()-1));
                        cardsOnTable.addCard(COMPUTER_player.getCard(comp_ONE.getCardCount()-1));
                        COMPUTER_player.removeCard(COMPUTER_player.getCardCount()-1);
    else if(cardsOnTable.getCardCount() != 0){
    table_combination = compCom.permutations(cardsOnTable, COMPUTER_player);
    //System.arraycopy(compCom.compareCards(COMPUTER_player),0,table_combination,0,compCom.compareCards(COMPUTER_player).length);
    outer:{
    if(table_combination == null){
    System.out.println(COMPUTER_name+" discards the " + COMPUTER_player.getCard(0));
                                  cardsOnTable.addCard(COMPUTER_player.getCard(0));
                                  COMPUTER_player.removeCard(0);
                                  break outer;
    I get the following error message when I compile the code just above.
    PlayScopa.java:283:cannot resolve symbol
    symbol : method lastIndexOf(Card, int)
    location: class java.util.ArrayList
    index = table_combination.lastIndexOf(COMPUTER_player.getCard(j), table_combination.size()-1);
    1 error
    well thats the problem, can anyone help

    ok here is the updated versionof the code
    (not all of it just the important parts)
    Iterator itr = ll.iterator();
         first:{
              while(itr.hasNext()){
                        key2 = String.valueOf(itr.next());
         //intKey = Integer.parseInt(key2);
                   for(int j=comp.getCardCount()- 1; j>=0;j++){
                        if(key2 == String.valueOf(comp.getCard(j).getValue())){
                             newArr = (ArrayList)ht.get(key2);
                             break first;
              if(!itr.hasNext()){
                   newArr = null;
    System.out.println("number of matches found");
         return newArr;
    the method that calls the snippit above is below
    ArrayList table_combination = null;
    int index = -1;
    table_Cards();
         System.out.println("Its "+COMPUTER_name+"'s turn");
         boolean z = true;
         if(cardsOnTable.getCardCount() == 0){
    System.out.println(COMPUTER_name+"??? discards the " + COMPUTER_player.getCard(COMPUTER_player.getCardCount()-1));
              cardsOnTable.addCard(COMPUTER_player.getCard(comp_ONE.getCardCount()-1));
              COMPUTER_player.removeCard(COMPUTER_player.getCardCount()-1);
    else if(cardsOnTable.getCardCount() != 0){
    table_combination = compCom.permutations(cardsOnTable, COMPUTER_player);
    outer:{
    if(table_combination == null){
    System.out.println(COMPUTER_name+" discards the " + COMPUTER_player.getCard(0));
                                  cardsOnTable.addCard(COMPUTER_player.getCard(0));
                                  COMPUTER_player.removeCard(0);
                                  break outer;
    The error message that I get is below again
    99.PICKUP a CARD from TABLE
    0
    z Discards the 7 of Diamonds
    Cards on the table are:
    0. 3 of Diamonds
    1. King of Spades
    2. King of Clubs
    3. King of Hearts
    4. 7 of Diamonds
    Its r's turn
    Exception in thread "main" java.lang.NullPointerException
    at Subsets.permutations(Subsets.java:108)
    at PlayScopa.computerTurn(PlayScopa.java:273)
    at PlayScopa.scopaPlay(PlayScopa.java:133)
    at PlayScopa.scopaStart(PlayScopa.java:89)
    at MainApp.main(MainApp.java:29)
    [u9zuh /home/stud3/csc99/u9zuh]$
    thats this null pointer about and how do I fix the problem

  • Dynamic DropDown not working.

    Hi All,
    I have to showup a dynamic Listbox.i was not able to figure out the where the problem is.
    JSP Code
    <htm:tr>
    <htm:td styleClass="dotted bdot" width="20%">
    <strong>State</strong><span class="warning">*</span></htm:td>     
    <htm:td styleClass="dotted bdot">
    <h:selectOneMenu id="selected_carrier_name"
    value={backing_newsi.selected_carrier_name}" >
    <f:selectItems value="#{backing_newsi.carrier_name}" />
    </h:selectOneMenu>
    </htm:td>
    </htm:tr>
    Backing Bean
    public List getCarrier_name()
    carrier_name=new LinkedList();
    ArrayList carrierinfodaolist= new ArrayList();
    carrierinfodaolist = sapmaindao.getCarrierInfoDAO();
    for (int i = 0; i < carrierinfodaolist.size(); i++)
    CarrierInfoDAO carrierinfodao= new CarrierInfoDAO();
    carrierinfodao = (CarrierInfoDAO)carrierinfodaolist.get(i);
    SelectItem item1 = new SelectItem(carrierinfodao.getCarrier_name().toString
    (),carrierinfodao.getCarrier_name().toString());
    carrier_name.add(item1);
    return carrier_name;
    I am getting the following error
    javax.servlet.jsp.JspException: Conversion Error setting value ''{0}'' for ''{1}''.
         at com.sun.faces.taglib.html_basic.SelectOneMenuTag.doEndTag(SelectOneMenuTag.java:515)
         at _newsi._jspService(_newsi.java:1477)
    I tried a lot... but could not able to do.. it.....
    anybody please help..me..
    Thanks..
    Arthi..!

    This error generally means that the value type of SelectItem isn't the same as the value type of the selected item, and that the JSF could not find an appropriate converter for it. Looking how you populated the #{backing_newsi.carrier_name}, the property behind #{backing_newsi.selected_carrier_name} should be of String type.

  • STRANGER RESULT

    Hi, the code below maps some objects to a key and then buts that key in to a linked list. When I compile and run this program I get a strange result can you help me please(note that more code is involved)
    public class Subsets {
         //Vector v = new Vector();
         Properties ht = new Properties();
         LinkedList ll = new LinkedList();
         ArrayList al1, al2, al3, al4, al5, al6, al7, al8;
         String           key = null;
         String           key2;
         int          intKey;
         //Card          cd[];
    ArrayList newArr = null;
         //Card vectArray[];
         //Card cd1[], cd2[], cd3[], cd4[], cd5[], cd6[], cd7[], cd8[];
    public ArrayList permutations(Hand dk, Hand comp){
         for (int f=0; f < dk.getCardCount(); f++){
              key = String.valueOf(dk.getCard(f).getValue());
              al1 = new ArrayList();
              al1.add(dk.getCard(f));
              ll.add(ht.put(key,al1));
              for (int s=f+1; s < dk.getCardCount(); s++){
                   key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue());
                   al2 = new ArrayList();
                   al2.add(dk.getCard(f));
                   al2.add(dk.getCard(s));
                   ll.add(ht.put(key, al2));
                   //v.addElement(ht.put(key,cd2));
                   for (int t=s+1; t < dk.getCardCount(); t++){
                        key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue());
                        al3 = new ArrayList();
                        al3.add(dk.getCard(f));
                        al3.add(dk.getCard(s));
                        al3.add(dk.getCard(t));
                        ll.add(ht.put(key,al3));
                        //v.addElement(ht.put(key,cd3));
                        for (int a=t+1; a < dk.getCardCount(); a++){
                             key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue());
                             al4 = new ArrayList();
                             al4.add(dk.getCard(f));
                             al4.add(dk.getCard(s));
                             al4.add(dk.getCard(t));
                             al4.add(dk.getCard(a));
                             ll.add(ht.put(key,al4));
                             //v.addElement(ht.put(key,cd4));
                             for (int b=a+1; b < dk.getCardCount(); b++){
                                  key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue()+dk.getCard(b).getValue());
                                  al5 = new ArrayList();
                                  al5.add(dk.getCard(f));
                                  al5.add(dk.getCard(s));
                                  al5.add(dk.getCard(t));
                                  al5.add(dk.getCard(a));
                                  al5.add(dk.getCard(b));
                                  ll.add(ht.put(key,al5));
                                  //v.addElement(ht.put(key,cd5));
                                  for (int c=b+1; c < dk.getCardCount(); c++){
                                       key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue()+dk.getCard(b).getValue()+dk.getCard(c).getValue());
                                       al6 = new ArrayList();
                                       al6.add(dk.getCard(f));
                                       al6.add(dk.getCard(s));
                                       al6.add(dk.getCard(t));
                                       al6.add(dk.getCard(a));
                                       al6.add(dk.getCard(b));
                                       al6.add(dk.getCard(c));
                                       ll.add(ht.put(key,al6));
                                       //v.addElement(ht.put(key,cd6));
                                       for (int d=c+1; d < dk.getCardCount(); d++){
                                            key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue()+dk.getCard(b).getValue()+dk.getCard(c).getValue()+dk.getCard(d).getValue());
                                            al7 = new ArrayList();
                                            al7.add(dk.getCard(f));
                                            al7.add(dk.getCard(s));
                                            al7.add(dk.getCard(t));
                                            al7.add(dk.getCard(a));
                                            al7.add(dk.getCard(b));
                                            al7.add(dk.getCard(c));
                                            al7.add(dk.getCard(d));
                                            ll.add(ht.put(key,al7));
                                            //v.addElement(ht.put(key,cd7));
                                            for (int e=d+1; e < dk.getCardCount(); e++){
                                                 key = String.valueOf(dk.getCard(f).getValue()+dk.getCard(s).getValue()+dk.getCard(t).getValue()+dk.getCard(a).getValue()+dk.getCard(b).getValue()+dk.getCard(c).getValue()+dk.getCard(d).getValue()+dk.getCard(e).getValue());
                                                 al8 = new ArrayList();
                                                 al8.add(dk.getCard(f));
                                                 al8.add(dk.getCard(s));
                                                 al8.add(dk.getCard(t));
                                                 al8.add(dk.getCard(a));
                                                 al8.add(dk.getCard(b));
                                                 al8.add(dk.getCard(c));
                                                 al8.add(dk.getCard(d));
                                                 al8.add(dk.getCard(e));
                                                 ll.add(ht.put(key,al8));
                                                 //v.addElement(ht.put(key,cd8));
         Iterator itr = ll.iterator();
         first:{
              while(itr.hasNext()){     
    // key2 = String.valueOf(itr.next());
    //System.out.println("key2 : "+key2);
    System.out.println("size "+ll.size());
    System.out.println("next "+itr.next());
    // intKey = Integer.parseInt(key2);
                   //for(int j=comp.getCardCount()-1; j>=0;j++){
                   //     if(intKey == comp.getCard(j).getValue()){
                   //          newArr = (ArrayList)ht.get(key2);
                   //          break first;
              if(!itr.hasNext()){
                   newArr = null;
    newArr = (ArrayList)ht.get(key2);
         return newArr;
    the result that I get is as follows
    Cards on the table are:
    0. 6 of Hearts
    1. 7 of Hearts
    2. 4 of Spades
    3. Jack of Spades
    4. 7 of Spades
    Its r's turn
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next [6 of Hearts, 7 of Hearts, 4 of Spades, Jack of Spades]
    size 31
    next [6 of Hearts, 7 of Hearts, 4 of Spades]
    size 31
    next null
    size 31
    next [6 of Hearts, 7 of Hearts, Jack of Spades]
    size 31
    next [6 of Hearts, 7 of Hearts]
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next null
    size 31
    next [6 of Hearts, 4 of Spades, Jack of Spades]
    size 31
    next null
    size 31
    next null
    size 31
    next [6 of Hearts, Jack of Spades]
    size 31
    next null
    size 31
    next null
    size 31
    next [7 of Hearts, 4 of Spades, Jack of Spades]
    size 31
    next [7 of Hearts, 4 of Spades]
    size 31
    next null
    size 31
    next [7 of Hearts, Jack of Spades]
    size 31
    next [7 of Hearts]
    Exception in thread "main" java.lang.NullPointerException
    at java.util.Hashtable.get(Hashtable.java:320)
    at Subsets.permutations(Subsets.java:124)
    at PlayScopa.computerTurn(PlayScopa.java:273)
    at PlayScopa.scopaPlay(PlayScopa.java:133)
    at PlayScopa.scopaStart(PlayScopa.java:89)
    at MainApp.main(MainApp.java:29)
    [u9zuh /home/stud3/csc99/u9zuh]$
    why are there gaps here
    not the for loops are as follows
    for(){
    ......for(){
    .............for(){
    .....................etc.....

    It's telling you exactly where the problem is:
    Exception in thread "main" java.lang.NullPointerException
    at java.util.Hashtable.get(Hashtable.java:320)
    at Subsets.permutations(Subsets.java:124)
    at PlayScopa.computerTurn(PlayScopa.java:273)
    at PlayScopa.scopaPlay(PlayScopa.java:133)
    at PlayScopa.scopaStart(PlayScopa.java:89)
    at MainApp.main(MainApp.java:29)
    What code is at line 124 of Subsets?
    When you figure out what line that is (use your IDE - Control-G often lets you type in a line number) look at the variables used on that line and see which one(s) hasn't been assigned a value.

  • Iterating performance: ArrayList, LinkedList, and Hashmap for N 1,000,000

    I have seen some websites discussing about the performance of ArrayLists, LinkedLists, and Hashmaps:
    http://forum.java.sun.com/thread.jspa?threadID=442985
    http://java.sun.com/developer/JDCTechTips/2002/tt0910.html
    http://www.javaspecialists.co.za/archive/Issue111.html
    http://joust.kano.net/weblog/archives/000066.html
    If I understand it right an ArrayList in general is faster for accessing a particular element in the collection and I can't find some pro's of using a LinkedList.
    My question is: If I only use a large collection with more than 1 million elements for iterating from begin to end (i.e. for loop), is it faster to use a linked list or a custom linked list instead of an arraylist (or hashmap)? Since you can iterate "directly" through a (custom) linked list, which is not possible with a arraylist?
    Edited by: 9squared on Nov 23, 2007 1:48 PM

    Thanks for the help, I wrote some code and tested it
    import java.util.ArrayList;
    import java.util.List;
    import java.util.LinkedList;
    public class TestTemp {
         public static void main(String[] args) {
              List<Node> a = new ArrayList<Node>();
              Node b = new Node("a");
              String[] c = new String[10000000];
              Node temp = b;
              for (int i = 0; i < 10000000; i++)
                   a.add(new Node("a"));
                   temp.next = new Node("b");
                   temp = temp.next;     
                   c[i] = "c";
              long tstart;
              tstart = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i++)
                   c[i] = "cc";
                   if (i%200000 == 0)
                        System.out.println("Array " + i + ": " + (System.currentTimeMillis()-tstart));
              tstart = System.currentTimeMillis();
              temp = b;
              for (int i = 0; i < 10000000; i++)
                   temp.next.text = "bb";
                   temp = temp.next;
                   if (i%200000 == 0)
                        System.out.println("LinkedList " + i + ": " + (System.currentTimeMillis()-tstart));
              tstart = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i++)
                   a.get(i).text = "aa";
                   if (i%200000 == 0)
                        System.out.println("ArrayList " + i + ": " + (System.currentTimeMillis()-tstart));
    public class Node {
         public String text;
         public Node next;
         public Node(String text)
              this.text = text;
    }Here are some results in milliseconds, and indeed just iterating doesn't take very long
    Elements     Linked     Arraylist     Array
    200000     0     0     1
    400000     5     13     5
    600000     9     22     9
    800000     14     32     12
    1000000     20     42     16
    1200000     25     52     19
    1400000     31     63     23
    1600000     37     72     26
    1800000     42     82     30
    2000000     47     92     33
    2200000     51     101     37
    2400000     56     112     40
    2600000     60     123     44
    2800000     65     134     47
    3000000     69     143     51
    3200000     73     152     55
    3400000     78     162     59
    3600000     84     175     63
    3800000     103     185     67
    4000000     108     195     70
    4200000     113     207     74
    4400000     117     216     78
    4600000     122     225     81
    4800000     127     237     85
    5000000     131     247     88
    5200000     136     256     92
    5400000     142     266     97
    5600000     147     275     101
    5800000     153     286     107
    6000000     159     298     113
    6200000     162     307     117
    6400000     167     317     121
    6600000     171     326     125
    6800000     175     335     128
    7000000     180     346     132
    7200000     184     358     136
    7400000     188     368     139
    7600000     193     377     143
    7800000     197     388     147
    8000000     201     397     150
    8200000     207     410     154
    8400000     212     423     157
    8600000     217     432     162
    8800000     222     442     167
    9000000     227     452     171
    9200000     231     462     175
    9400000     236     473     178
    9600000     242     483     182
    9800000     249     495     185
    10000000     257     505     189

  • Which is better? ArrayList or LinkedList

    Do you know which one is better between ArrayList and LinkdedList in terms of performance, speed and capacity?
    Which one do you suggest to use ?
    Thanks

    It depends upon how the list is going to be used. ArrayLists and LinkedLists work differently -- you need to think about how they each store their data.
    ArrayLists store their list items in, well, arrays. This makes them very fast at addressing those items by index #. So any implementation that needs a lot of random access to the list, such as sorting, is going to be relatively fast.
    The downside of storing the list in an array presents itself when it comes time to add more items to the list. When it runs out of space in the array, it must create a new larger array and copy the items over to it. Also, if you need to insert or remove an item anywhere other than the end of the list, ArrayList must shift the subsequent items in the list by doing an array copy.
    This can be a real drag if you're implementing a queue. This is where LinkedList shines. Each item in the list points to the next and previous ones in the list. Inserting, appending or removing list items involves a couple simple assignment statements. No reallocations or large memory copies are involved. Access is easy as long as it is sequential.
    Random access in a linked list is problematic however. In order to get to the Nth item in the list, LinkedList must start with the first item in the list and step through the list N-1 times. An order of magnitude slower than using an ArrayList.

  • Design choice between ArrayList and LinkedList

    Can someone clarify me which is better suited (efficient) for use?
    It appears to me that both can be used very much interchangeably at least from functionality point of view. :(

    Using the following code (and I'm sure someone will come nitpicking about it) I get the (expected, at least by me from prior experience) result that iteration over a LinkedList is about twice as fast as iteration over an ArrayList, but lookup operations on an ArrayList are substantially faster:
    package jtw.test;
    import java.util.*;
    public class SpeedTest {
        public static void main(String... args) throws Exception {
            List<Integer> linked = new LinkedList<Integer>();
            List<Integer> arr = new ArrayList<Integer>();
            for (int i = 0; i < 1e3; i++) {
                linked.add(i);
                arr.add(i);
            long r = 0;
            Date startLinked = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (Integer q: linked) {
                     r += q;
            Date stopLinked = new Date();
            System.out.println("Total: " + r);
            r = 0;
            Date startArr = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (Integer q: arr) {
                     r += q;
            Date stopArr = new Date();
            System.out.println("Total: " + r);
            System.out.println("LinkedList iteration: " + startLinked + " to " + stopLinked + " took " + (stopLinked.getTime() - startLinked.getTime()));
            System.out.println(" ArrayList iteration: " + startArr + " to " + stopArr + " took " + (stopArr.getTime() - startArr.getTime()));
             r = 0;
            startLinked = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (int j = 999; j >= 0; j--) {
                     r += linked.get(j);
            stopLinked = new Date();
            System.out.println("Total: " + r);
            r = 0;
            startArr = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (int j = 999; j >= 0; j--) {
                     r += arr.get(j);
            stopArr = new Date();
            System.out.println("Total: " + r);
            System.out.println("LinkedList lookup: " + startLinked + " to " + stopLinked + " took " + (stopLinked.getTime() - startLinked.getTime()));
            System.out.println(" ArrayList lookup: " + startArr + " to " + stopArr + " took " + (stopArr.getTime() - startArr.getTime()));
    }Gets the result:
    D:\jdk1.6.0_05\bin\java -Didea.launcher.port=7540 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 8.0.1\bin" -Dfile.encoding=windows-1252 -classpath "D:\jdk1.6.0_05\jre\lib\charsets.jar;D:\jdk1.6.0_05\jre\lib\deploy.jar;D:\jdk1.6.0_05\jre\lib\javaws.jar;D:\jdk1.6.0_05\jre\lib\jce.jar;D:\jdk1.6.0_05\jre\lib\jsse.jar;D:\jdk1.6.0_05\jre\lib\management-agent.jar;D:\jdk1.6.0_05\jre\lib\plugin.jar;D:\jdk1.6.0_05\jre\lib\resources.jar;D:\jdk1.6.0_05\jre\lib\rt.jar;D:\jdk1.6.0_05\jre\lib\ext\dnsns.jar;D:\jdk1.6.0_05\jre\lib\ext\localedata.jar;D:\jdk1.6.0_05\jre\lib\ext\sunjce_provider.jar;D:\jdk1.6.0_05\jre\lib\ext\sunmscapi.jar;D:\jdk1.6.0_05\jre\lib\ext\sunpkcs11.jar;F:\dev\Euler\out\production\Euler;C:\Program Files\JetBrains\IntelliJ IDEA 8.0.1\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain jtw.test.SpeedTest
    Total: 499500000
    Total: 499500000
    LinkedList iteration: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:41 CET 2009 took 30
    ArrayList iteration: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:41 CET 2009 took 53
    Total: 499500000
    Total: 499500000
    LinkedList lookup: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:42 CET 2009 took 424
    ArrayList lookup: Wed Jan 21 07:32:42 CET 2009 to Wed Jan 21 07:32:42 CET 2009 took 22
    Process finished with exit code 0Given the internal representation of the datatypes, this is to be expected.

  • A suggestion : use "loop array list" instead of ArrayList / LinkedList

    ArrayList is good at:
    get / set by index : O(1)
    appending : O(log(n))
    remove last : O(1)
    and very bad at:
    add middle : O(n)
    remove from middle : O(n)
    LinkedList is good at:
    fast remove from middle, if your iteraror already goes there : O(1)
    convenient methods : addFirst, addLast, removeFirst, removeLast : O(1)
    and very bad at :
    get / set by index : O(n)
    here I want to make a suggestion : use "loop array list" instead of the ArrayList and LinkedList.
    a "loop array list" is based on array, just like ArrayList. But it has 2 member-variables : the start position, and the real size. the start position can be anywhere within array.length. an element of index "i" is stored in array[ start + i ], and when (start + i > array.length), loop to the beginning of the array; when (start + i < 0), loop to the end of the array.
    this "loop array list" has all the good sides:
    get / set by index : O(1)
    add first / last : O(log(n))
    remove first / last : O(log(n))
    add / remove from middle : O(n)
    (note : because we shrink the backup-array when the real size is too small, add / remove operation take O(log(n)) now.)
    the only problem is : add / remove from middle. let's take a look at it.
    1. the LinkedList does NOT really add/remove from middle in O(1), you has to locate the element, which is O(n).
    2. O(n) is acceptable, O(n^2) is not acceptable. try this : keep removing first element from an very big ArrayList ( size>10^6 ) until it's empty.
    the fact is, any list can perform batch-remove / batch-add operation in O(n) instead of O(n^2). it's easy : allocate a new list, iterate the original list, copy the element into the new list if condition is satisfied.
    so, instead of "remove from middle", what we need is a new methods : removeAllByCondition( Condition condition ), and now the batch-remove operation can be done in O(n)
    here is an implementation of mine. I've tested it on my computer( 512mem + 2G cpu, win2k + jdk1.5 ), it's amazing, just a little slower then ArrayList when add last, and a liitle slower then LinkedList when batch-remove. in all other cases, it's far more better then those 2 kinds of List.
    // source code : List2
    import java.util.AbstractList;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.NoSuchElementException;
    import java.util.Set;
    public final class List2<T> extends AbstractList<T> {
    private static int initialArrayLength = 4;
    private T[] array;
    private int start;
    private int size;
    private void init( T[] newArray, int start_a, int size_a ) {
    array = newArray;
    start = start_a;
    size = size_a;
    @SuppressWarnings("unchecked")
    private void init() {
    init( (T[]) new Object[ initialArrayLength ], 0, 0 );
    public List2() {
         init();
    @SuppressWarnings("unchecked")
    public List2( Collection<? extends T> collection ) {
         init(
              collection.toArray( (T[]) new Object[ collection.size() * 11 / 10 + 1 ] ),
              0,
              collection.size()
    private List2( T[] array_a, int start_a, int size_a ) {
         init( array_a, start_a, size_a );
    @SuppressWarnings("unchecked")
    public static <TT> List2<TT> createV( TT... elements ) {
         TT[] array = (TT[]) new Object[ elements.length * 11 / 10 + 1 ];
         System.arraycopy( elements, 0, array, 0, elements.length );
         return new List2<TT>( array, 0, elements.length );
    public static List2<Double> create( double... elements ) {
         Double[] array = new Double[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array[i] = elements;
         return new List2<Double>( array, 0, elements.length );
    public static List2<Integer> create( int... elements ) {
         Integer[] array2 = new Integer[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Integer>( array2, 0, elements.length );
    public static List2<Character> create( char... elements ) {
         Character[] array2 = new Character[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Character>( array2, 0, elements.length );
    public static List2<Character> create( String s ) {
         return create( s.toCharArray() );
    public List2<T> clone() {
         return new List2<T>( this );
    // basic
    public int size() {
         return size;
    private int index( int index ) {
         int i = start + index;
         if( i >= array.length )
              i -= array.length;
         return i;
    public T get( int d ) {
         if( d < 0 || d >= size )
              throw new IndexOutOfBoundsException();
         if( size == 0 )
              throw new NoSuchElementException();
         return array[ index( d ) ];
    public T set( int index, T element ) {
         if( index < 0 || index >= size )
              throw new IndexOutOfBoundsException();
         int i = index( index );
         T oldElement = array[i];
         array[i] = element;
         return oldElement;
    @SuppressWarnings("unchecked")
    private void copyAndSetToNewArray( int newArrayLength ) {
         T[] newArray = (T[]) new Object[ newArrayLength ];
         for( int i=0; i<size; i++ )
              newArray[i] = array[ index( i ) ];
         init( newArray, 0, size );
    public void addFirst( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         int i = index( array.length - 1 );
         array[ i ] = element;
         start = i;
         size++;
    public void addLast( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         array[ index( size ) ] = element;
         size++;
    public T removeFirst() {
         if( size == 0 )
              throw new NoSuchElementException();
         T oldElement = array[ start ];
         array[ start ] = null;
         start = index( 1 );
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    public T removeLast() {
         if( size == 0 )
              throw new NoSuchElementException();
         int i = index( size - 1 );
         T oldElement = array[i];
         array[i] = null;
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    @SuppressWarnings("unchecked")
    public int removeAll( ListCondition<T> condition ) {
         T[] newArray = (T[]) new Object[ array.length ];
         int iNew = 0;
         for( int i=0; i < size; i++ ) {
              T element = get( i );
              if( ! condition.isConditionSatisfied( this, i, element ) )
                   newArray[ iNew++ ] = element;
         int oldSize = size;
         init( newArray, 0, iNew );
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return size - oldSize;
    // aux
    public boolean equals(Object obj) {
         if( obj == this )
         return true;
         if( obj instanceof List2 ) {
              List2 that = (List2) obj;
              if( this.size != that.size )
                   return false;
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], that.array[ that.index(i) ] ) )
                        return false;
              return true;
         if( obj instanceof List ) {
              List that = (List) obj;
              if( this.size != that.size() )
                   return false;
              Iterator thatIter = that.iterator();
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], thatIter.next() ) )
                        return false;
              return true;
         return true;
    public int hashCode() {
         int hashCode = 1;
         for( int i=0; i < size; i++ ) {
              T element = array[ index( i ) ];
         hashCode = 31*hashCode + ( element==null ? 0 : element.hashCode() );
         return hashCode;
    public boolean isEmpty() {
         return size == 0;
    public T getFirst() {
         return get( 0 );
    public T getLast() {
         return get( size() - 1 );
    public T getRandom() {
         return get( (int) (Math.random() * size) );
    public int indexOf( Object element ) {
         for( int i=0; i < size; i++ )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public int lastIndexOf( Object element ) {
         for( int i=size-1; i >= 0; i-- )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public boolean contains( Object element ) {
         return indexOf( element ) != -1;
    public boolean add( T element ) {
         addLast( element );
         return true;
    @Deprecated
    public void add( int index, T element ) {
         throw new UnsupportedOperationException();
    public T remove() {
         return removeFirst();
    @Deprecated
    public boolean remove( Object element ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    @Deprecated
    public T remove( int index ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    public void clear() {
         init();
    public Object[] toArray() {
         Object[] result = new Object[ size ];
         for( int i=0; i < size; i++ )
         result[i] = array[ index( i ) ];
         return result;
    @SuppressWarnings("unchecked")
    public <TT> TT[] toArray( TT[] a ) {
    if( a.length < size )
    a = (TT[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size );
    for( int i=0; i < size; i++ )
    a[i] = (TT) array[ index( i ) ];
    if( a.length > size )
         a[size] = null;
    return a;
    @SuppressWarnings("unchecked")
    public void sort() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0; i < size; i++ )
              array[ i ] = (T) a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = (T) a[ j ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sort( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0; i < size; i++ )
              array[ i ] = a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = a[ j ];
         start = 0;
    public String toString( String delimiter ) {
         return toString( "", delimiter, "", size() );
    public String toString( String prefix, String delimiter, String suffix, int max ) {
         StringBuffer stringBuffer = new StringBuffer( prefix );
         int dest = Math.min( max, size );
         for( int i=0; i < dest; i++ ) {
              stringBuffer.append( get(i) );
              if( i < dest - 1 )
                   stringBuffer.append( delimiter );
         if( size > max )
              stringBuffer.append( "...(" ).append( size() - max ).append( " more)" );
         stringBuffer.append( suffix );
         return stringBuffer.toString();
    // batch operation
    public boolean containsAll( Collection<?> that ) {
         Set<Object> thisSet = new HashSet<Object>( this );
         for( Object element : that )
              if( ! thisSet.contains( element ) )
                   return false;
         return true;
    @SuppressWarnings("unchecked")
    public List2<T> subList( int fromIndex, int toIndex ) {
         if( fromIndex < 0 || toIndex > size || toIndex < fromIndex )
              throw new IndexOutOfBoundsException();
         int newSize = toIndex - fromIndex;
         T[] newArray = (T[]) new Object[ newSize * 11 / 10 + 1 ];
         for( int i=fromIndex, iNew=0; i < toIndex; i++, iNew++ )
              newArray[ iNew ] = array[ index( i ) ];
         return new List2<T>( newArray, 0, newSize );
    public void addV( T... that ) {
         for( T element : that )
              addLast( element );
    public boolean addAll( Collection<? extends T> that ) {
         for( T element : that )
              addLast( element );
         return ! that.isEmpty();
    @Deprecated
    public boolean addAll( int index, Collection<? extends T> c ) {
         throw new UnsupportedOperationException();
    public void removeRest( T element ) {
         int position = lastIndexOf( element );
         if( position == -1 )
              return;
         while( ! Tools.equals( element, removeLast() ) );
    public void removeAllEquals( final T element ) {
         removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T currentElement) {
              return currentElement.equals( element );
    public void removeAllBetween( final T from, final T to ) {
         removeAll( new ListCondition<T>() {
              @SuppressWarnings("unchecked")
              public boolean isConditionSatisfied(List2 list, int index, T element) {
                   if( from != null && ((Comparable) from).compareTo( element ) > 0 )
                        return false;
                   if( to != null && ((Comparable) to).compareTo( element ) <= 0 )
                        return false;
                   return true;
    public boolean retainAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return ! thatSet.contains( element );
         return removeCount > 0;
    public boolean removeAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return thatSet.contains( element );
         return removeCount > 0;
    // unit test
    private static int maxTestCount = 1000 * 1000;
    public static void unitTest() throws Exception {
         // thest thoese methods for one time
         Tools.ensureEquals( new List2(), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), List2.create( "abcdef" ) );
         final List<Double> list1 = new ArrayList<Double>();
         final List2<Double> list2 = new List2<Double>();
         Runnable[] tasks = new Runnable[] {
              // test those methods that do NOT change the list
              new Runnable() { public void run() {
                   Tools.ensureEquals( new List2<Double>( list1 ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray() ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray( new Double[0] ) ), list1 );
                   double[] doubles = new double[ list1.size() ];
                   int i = 0;
                   for( double d : list1 )
                        doubles[i++] = d;
                   Tools.ensureEquals( List2.create( doubles ), list1 );
                   Tools.ensure( list1.isEmpty() == list2.isEmpty() );
                   Arrays.equals( list1.toArray(), list2.toArray() );
                   Tools.ensureEquals( list1, list2.clone() );
                   Double notExistElement = -2.0;
                   Tools.ensure( list1.indexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.lastIndexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.contains( notExistElement ) == false );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.hashCode(), list2.hashCode() );
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.get(0).equals( list2.getFirst() ) );
                   Tools.ensure( list1.get(list1.size()-1).equals( list2.getLast() ) );
                   Double existRandomElement = list2.getRandom();
                   Tools.ensure( list1.contains( existRandomElement ) );
                   Tools.ensure( list2.contains( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   int from = (int) (Math.random() * list1.size());
                   int to = (int) (Math.random() * (list1.size()+1));
                   if( from > to ) {
                        int t = from;
                        from = to;
                        to = t;
                   Tools.ensureEquals( list1.subList( from, to ), list2.subList( from, to ) );
              // test those methods that change the list
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   double d = Math.random();
                   list1.set( i, d );
                   list2.set( i, d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   Tools.ensure( list1.get( i ).equals( list2.get( i ) ) );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( 0, d );
                   list2.addFirst( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( 0 ).equals( list2.removeFirst() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( list1.size() - 1 ).equals( list2.removeLast() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = 0;
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); i++ ) {
                        iter.next();
                        if( i % 3 == 0 )
                             iter.remove();
                   list2.removeAll( new ListCondition<Double>() { public boolean isConditionSatisfied(List2 list, int index, Double element) {
                        return index % 3 == 0;
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.add( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove(0).equals( list2.remove() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int r = (int) (Math.random() * list1.size());
                   Double element = list1.get( r );
                   int index = list1.lastIndexOf( element );
                   for( int i=list1.size()-1; i>=index; i-- )
                        list1.remove( i );
                   list2.removeRest( element );
              new Runnable() { public void run() {
                   list2.removeRest( Math.random() - 2 );
              new Runnable() { public void run() {
                   list1.clear();
                   list2.clear();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   list2.sort();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   Collections.reverse( list1 );
                   list2.sortDesc();
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   list2.sort( comparator );
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   Collections.reverse( list1 );
                   list2.sortDesc( comparator );
              new Runnable() { public void run() {
                   Double notExistElement = -2.0;
                   list2.removeAllEquals( notExistElement );
                   Tools.ensureEquals( list1, list2 );
                   list2.removeAllBetween( 0.5, 0.6 );
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); ) {
                        double d = iter.next();
                        if( d >= 0.5 && d < 0.6 )
                             iter.remove();
                   Tools.ensureEquals( list1, list2 );
         System.out.print( "test List2 " );
         for( int i=0; i < maxTestCount; i++ ) {
              tasks[ (int) (Math.random() * tasks.length) ].run();
              Tools.ensureEquals( list1, list2 );
              if( i % (maxTestCount/10) == 0 )
                   System.out.print( "." );
         System.out.println( " ok" );
    // source code : ListCondition
    public interface ListCondition<T> {
    boolean isConditionSatisfied( List2 list, int index, T element );

    Hi,
    I have the following statement:
    private List list = new ArrayList();
    why not use private ArrayList list = new
    ArrayList()?
    I know ArrayList implements List, so list has a wide
    scope, right? What's the benefit?
    Thanks,
    JieBy using the interface you are not tied to a specific implementation.
    Later, you may determine that using a LinkedList is more efficient to your specific code and then all you need to do is change the statement to:
    private List list = new LinkedList();As long as you are not casting the list reference to ArrayList (or something along those lines) you would not need to change anything else.

  • Plz help! how to create a LinkedList inside each element of ArrayList

    how do i create a LinkedList inside each element of ArrayList

    how do i create a LinkedList inside each element of
    ArrayListYou really should read the API documentation and if you would you would see that you can construct a new ArrayList like this:
    ArrayList list = new ArrayList();and you can add to it like this
    list.add(new LinkedList());and now your list contains a new LinkedList at position 0 wich of course would be a LinkedList with some purpose not just a new empty one like in the example above. You could do something like this:
    ArrayList list = new ArrayList();
    LinkedList linkedList1=new LinkedList();
    // add something to linkedList1
    list.add(linked);
    LinkedList linkedList2=new LinkedList();
    // add something to linkedList2
    list.add(linked);
    LinkedList linkedList3=new LinkedList();
    // add something to linkedList3
    list.add(linked);and so one..
    bopen, hope this helps

  • ArrayList vs LinkedList

    Can anyone explain with a real time example where these will be used , & whats the difference between them....
    1 ) ArrayList (vs) LinkedList (vs) Collection
    2 ) Abstract Class (vs) Interface

    Some more to add to that .,
    Abstract class vs Interfaces
    Extending threads vs Implementing runnable interface
    HashTable vs HashMap
    Iterator vs Enumeration
    string vs StringBuffer
    Reflections vs Introspection
    Array vs Vector
    ArrayList vs LinkedList
    Throw vs Throws
    can anyone help me in this regard?Most or all of these should be addressed in one of the following or in a google search of the exact terms. Do some research on your own, and then come back with more specific questions. These forums are not a particularly effective substitute for attending class or reading a textbook.
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.

  • Both of the advantages of ArrayList and LinkedList are needed.

    Hi there,
    I wonder how if I want performance on random access an ArrayList and also remove elements in any position of the List? As far as I know that a LinkedList is the best choice if I want to remove elements in any position of the List, but it's slow on traversing the List. Sometimes it's hard to choose between ArrayList and LinkedList, is there a way that I could have both advantages of ArrayList and LinkedList?
    Any suggestion?
    Thanks,
    Jax

    I think you might be interested in the data structure
    called a deque. It is built for fast insertions
    at both ends and is usually implemented as a linked
    list of arrays. The standard collections API does not
    offer this data structure (I wish it did). So you have
    to find a 3rd party implementation. Try searching
    Google: http://www.google.com/search?q=java+deque
    Thanks nasch and pervel for the information. What do you think if I do something like this?
    List a = new ArrayList();
    // perform some tasks that is fast with ArrayList
    List b = new LinkedList(a);
    // perform some tasks..
    Although a new object is created, but that perform better than one ArrayList or one LinkedList solely.

Maybe you are looking for

  • Using newText more than once in a form

    I have a form with several hidden subforms, which become visible depending on what the user selects in the dropdown list for each subform. The problem is that my script doesn't work for all the subforms. I've come across some information about this (

  • Vendor code 12154 and 1005 error

    Hi, I have developed an application which users the RDC API set (CR XI R2 SP4.5 version) to preview crystal reports. All types of reports works fine but except one. This report is a blank report with one sub-report. I have used native oracle connecti

  • A Tiger Software Update Question from the iBook Forum

    I just finished reading this question, http://discussions.apple.com/thread.jspa?messageID=12901184#12901184 in the iBook G4 forum and am very curious myself if this could be a problem with the update. If someone knows why this is happening, would you

  • Getting error with SQL statement

    Hi I am getting these error java.sql.SQLException: Non supported SQL92 at the time time of executing the query. select distinct state from cities where country = ${COUNTRY} this query is using in my JasperReport tool. Why I am getting this error coul

  • Selling stuff of online game

    Hello so i was selling stuff of online game and now i got limited and i have to Provide Invoices they ask me this Please confirm that you own the merchandise you're selling. Helpful documents include copies of sales receipts, itemized lists of goods