Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    1
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Sorting an array of objects

    I'm working on a card game, and I need to sort an array that contains card objects. The array needs to be sorted based on the numerical value of each card in ascending order. I have a method, getValue, that returns the value of the card at the element that the method is called upon.

    But, I am unsure of how exactly to sort the data correctly, as I am not too familiar with sorting in Java. Any help would be great.

    EDIT: Actually, I just figured it out on my own. I just created a new array that contained just the numerical values of the array of cards. Then I just simply sorted that array of ints, since in this case I only cared about the value of the cards, not the suit.
    Last edited by ADAMWD; 11-13-2010 at 04:05 AM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    The multiple array juggling will work, but it will become more complicated as you get more and more dimensions.
    Sorting objects in Java is very easy. A flat array uses the static Arrays.sort method in combination with a Comparator<T> or a class of type Comparable<T>. So with your Card class:
    PHP Code:
    public class Card implements Comparable<Card>
    {
        
    // Whatever card stuffs
        
    public int compareTo(Card b)
        {
            return 
    a.getValue() - b.getValue(); // These can be just the members
        
    }

        public 
    boolean equals(Object other)
        {
            
    boolean bResult false;
            if (
    other instanceof Card)
            {
                
    bResult = (this.compareTo((Card)other) == 0);
            }
            return 
    bResult;
        }

    Then in a main method, my card array will be called cards:
    Code:
    Arrays.sort(cards);
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • Users who have thanked Fou-Lu for this post:

    ADAMWD (11-13-2010)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •