collections - Java Sorting object in ArrayList -


Hello I have a card class ... in the second category I create an array list of the card object. How do I sort the array list based on the value of the card? Ace is the lowest card value and the king is the highest.

A, 2,3,4,5,6,7,8,9, T, J, Q

  public class card {rank of variable, Suit; Public card (four ranks, four suits) {this.rank = rank; This.suit = suit; } Public Zero Setcard (four ranks, four suits) {this.rank = rank; This.suit = suit; } Public charity score () {Return rank; } Public Stories Mill (Suite) {Suit; } Public Zero Sitank (four ranks) {this.rank = rank; } Public Zero Setset (four suits) {this.suit = suit; } Public string toString () {string str = ""; Str + = this.getRank (); Str + = this.getSuit (); Return str; } Public boolean equivalent (object obj) {card card = (card) obj; If (this.rank == card.getRank ()) & amp; This.suit == card.getSuit ()) {back true; }                return false; } Public boolean is ValidCard (card card) {char s = card.getSuit (); Char r = card.getRank (); If (S == 'H' || S == 'S' || S == 'D' || S == 'C') (If (R == 'A' || R == '2' || R == '3' || R == '4' || R == '5' || R == '6' || R == '7' || R == '8' || R == '9' || R == 't' || R == 'J' || R == 'Q' || R == 'K') {Back true;}} Description is false;} Public boolean permissions inhiger file (card card, game game, int heap) {if (pile> = 5 & amp; amp; amp; game.getPile (pile). Cards.size () == 0) {if ( Card.getRank ()! = 'K') false return;} Back to true; One option is to apply comparative interface and after that Do not override it once is easy to list with 'collection. Collection (myCollection); 

You can be better off implementing comparative and building objects, and collection of There is one version.

Your comparison function can only check the rank of the card, and return the result when ignoring the suit.

You may want to read the Java tutorial .

Update: Bjerne correctly So that should be comparative use when there is a natural sorting order in class. My personal view is that there is not really a "natural order" for the card because there is a variation in the different game Ace in its interpretation, so to avoid assigning "semantically" as part of the class. can improve.


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -