javasorting

Java Insertion Sort with an Array List of objects?


I have a class Card which contains value (int), suit (String) and faceValue (String). It seems like a regular insertion sort on Card.value should work fine. I just use the whole object when moving things around. For some reason, this crashes and burns. It ends up duplicating the highest card into every element except for a random element that I can't understand.

value, suit, and faceValue are pulic, also.

This is my code:

public static void insertionSort(ArrayList<Card> Array) {

    int i,j;
    Card key = new Card(0, "","");

    for (i = 1; i < Array.size(); i++) {
        key.value = Array.get(i).value;
        key.suit = Array.get(i).suit;
        key.faceValue = Array.get(i).faceValue;
        j = i;
        while((j > 0) && (Array.get(j - 1).value > key.value)) {
            Array.set(j,Array.get(j - 1));
            j--;
        }
        Array.set(j,key);
    }


}

I checked this against Wikipedia's pseudo code, and I can't find any fundamental difference. I've been through the debugger a dozen times, and I can't see any reason for the compiler to do what it's doing. Does anyone have an idea why it's not working?

Thanks.


Solution

  • At every cycle, you insert the object "key" into the list (Array.set(j,key);). So, at the end your whole list will be made of references to the object "key". So when you set key.value, key.suit and key.faceValue at the end, you are setting the fields of every element of your list, because your list consists of references of the same object.

    move Card key = new Card(0, "",""); inside the for loop. Like this:

    public static void insertionSort(ArrayList<Card> Array) {
    
        int i, j;
    
        for (i = 1; i < Array.size(); i++) {
            Card key = new Card(0, "","");
            key.value = Array.get(i).value;
            key.suit = Array.get(i).suit;
            key.faceValue = Array.get(i).faceValue;
            j = i;
            while((j > 0) && (Array.get(j - 1).value > key.value)) {
                Array.set(j,Array.get(j - 1));
                j--;
            }
            Array.set(j,key);
        }
    
    
    }
    

    gl with your studies :)