Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
Thread: Sorting an array of objects
11-13-2010, 03:53 AM #1
- Join Date
- Nov 2010
- 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.
11-13-2010, 03:56 PM #2
- Join Date
- Sep 2002
- Saskatoon, Saskatchewan
- Thanked 2,660 Times in 2,629 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:
Then in a main method, my card array will be called cards: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);
header('HTTP/1.1 420 Enhance Your Calm');
Users who have thanked Fou-Lu for this post: