【问题标题】:Java Sorting object in ArrayListArrayList 中的 Java 排序对象
【发布时间】:2009-04-26 19:20:32
【问题描述】:

嗨,我有 Card 类...在另一个类中,我创建了 Card 对象的 arrayList。我将如何根据卡的值对 arrayList 进行排序? A 是最低的牌值,K 是最高的牌。

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

public class Card {

        char rank, suit;

        public Card(char rank, char suit){
                this.rank = rank;
                this.suit = suit;
        }

        public void setCard(char rank, char suit){
                this.rank = rank;
                this.suit = suit;
        }

        public char getRank(){
                return rank;
        }

        public char getSuit(){
                return suit;
        }

        public void setRank(char rank){
                this.rank = rank;
        }

        public void setSuit(char suit){
                this.suit = suit;
        }


        public String toString(){
                String str = "";
                str += this.getRank();
                str += this.getSuit();
                return str;
        }

          public boolean equals(Object obj){
               Card card = (Card) obj;
               if(this.rank == card.getRank() && this.suit == card.getSuit()){
                   return true;
               }
               return false;
           }

    public boolean isValidCard(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'){
                return true;
            }                   
        }
        return false;
     }

    public boolean allowedInHigherPiles(Card card, Game game, int pile){
        if(pile>=5 && game.getPile(pile).cards.size()==0){
                if(card.getRank()!='K')
                        return false;
        }
        return true;
    }

}

【问题讨论】:

    标签: java collections


    【解决方案1】:

    如果您使用枚举而不是字符来表示等级和套件,代码会更简洁。

    其实http://jcp.org/aboutJava/communityprocess/jsr/tiger/enum.html有一个Card sample说明了Enum的使用

    相关代码位复制如下

    public class Card implements Comparable, java.io.Serializable {
        public enum Rank { deuce, three, four, five, six, seven, eight, nine, ten,
                           jack, queen, king, ace }
        public enum Suit { clubs, diamonds, hearts, spades }
    
        private final Rank rank;
        private final Suit suit;
    
        private Card(Rank rank, Suit suit) {
            if (rank == null || suit == null)
                throw new NullPointerException(rank + ", " + suit);
            this.rank = rank;
            this.suit = suit;
        }
    
        public Rank rank() { return rank; }
        public Suit suit() { return suit; }
    
        public String toString() { return rank + " of " + suit; }
    
        public int compareTo(Object o) {
            Card c = (Card)o;
            int rankCompare = rank.compareTo(c.rank);
            return rankCompare != 0 ? rankCompare : suit.compareTo(c.suit);
        }
    
        private static List<Card> sortedDeck = new ArrayList<Card>(52);
        static {
            for (Iterator<Rank> i = Rank.VALUES.iterator(); i.hasNext(); ) {
                Rank rank = i.next();
                for (Iterator<Suit> j = Suit.VALUES.iterator(); j.hasNext(); )
                    sortedDeck.add(new Card(rank, j.next()));
            }
        }
    
        // Returns a shuffled deck
        public static List<Card> newDeck() {
            List<Card> result = new ArrayList<Card>(sortedDeck);
            Collections.shuffle(result);
            return result;
        }
    }
    

    【讨论】:

    • 您可以调用 One => Ace 和十三 => King 等。 ;)
    • 最终标准是使用 AOL-shouty-retard-case 作为枚举实例名称。使 Card 不可变是个好主意。
    • Java 的 Enum 介绍页面也给出了卡片示例 java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
    • Comparable 也是泛型类型。所以你的代码应该更像这样: public class Card implements Comparable, java.io.Serializable { //... public int compareTo(Card c) { int rankCompare = rank.compareTo(c.rank);返回排名比较!= 0? rankCompare : suit.compareTo(c.suit); } }
    【解决方案2】:

    一种选择是实现 Comparable 接口,然后覆盖 compareTo 完成后,使用 Collections.sort(myCollection); 对列表进行排序很容易

    您最好避免实现 Comparable 并创建一个 Comparator 对象,并且有一个 Collections.sort 版本可以使用比较器。

    然后您的比较函数可以简单地检查牌的等级,并在忽略花色的情况下返回结果。

    您可能想阅读all this ordering business 上的 Java 教程。

    更新:Bjorn 正确地指出,当类具有自然排序顺序时,应该使用 Comparable。我个人的观点是,对于纸牌并没有真正的“自然顺序”,因为不同的游戏对 Ace 的解释不同,因此最好通过提供 Comparable 作为类的一部分来避免分配“语义”。

    【讨论】:

    • 由于一副纸牌具有自然的排序顺序,我建议在单独的 Comparator 类上使用 Comparable 接口。当对象没有自然排序顺序时,应使用比较器类,如 Shoe 类。不同的人以不同的方式(按颜色、尺码、价格)对鞋子进行分类。 :-)
    • Bjorn:我同意,除了王牌的角色在许多游戏(例如 BJ 和扑克)中会发生变化,所以我会小心为卡片添加语义。
    【解决方案3】:

    缺少的 CompareTo 代码:

    ArrayList<Card> aCardList = new ArrayList<Card>();
    
        Collections.sort(aCardList, new Comparator<Card>() {
    
            @Override
            public int compare(Card o1, Card o2) {
                if (o1.getRank() > o2.getRank())
                    return -1;
                else if (o1.getRank() < o2.getRank())
                    return 1;
                else
                    return 0;
            }
        });
    

    【讨论】:

      【解决方案4】:

      您可以实现Comparable 接口,以便按等级比较元素。然后Collections.sort 会自动做你期望它做的事情。

      【讨论】:

        【解决方案5】:

        几个更短的方法

        public String toString() {
           return "" + rank + suit;
        }
        
        public boolean isValidCard(){
            return "HSDC".indexOf(suit) != -1 &&
                 "A23456789TJQK".indexOf(rand) != -1;
        }
        

        【讨论】:

          【解决方案6】:

          您可以使用java.util.Collections 类对其进行排序。特别是,两种方法可能会派上用场:

           static <T extends Comparable<? super T>>
           void sort(List<T> list)
                Sorts the specified list into ascending order, according to the natural ordering of its elements.
          
          static <T> void sort(List<T> list, Comparator<? super T> c)
                Sorts the specified list according to the order induced by the specified comparator.
          

          对于第一种方法,你应该让你的 Card 类实现 Comparable 接口。 对于第二个,您应该提供一个自定义比较器。

          这样做是为了让集合框架知道如何比较您的 Card 对象。

          因此,例如(第一种方法),您将拥有以下代码:

          在你的卡片类中

          public Class Card implements Comparable{
          
          //member and method definitions.
          
          public int compareTo(Object o){
             //null checks && stuff missing.
          
             /*compares two cards based on rank.*/   
          }
          
          List<Card> cards = getAllCards();//returns an unsorted list implementation of Card objects.
          
          java.util.Collections.sort(cards);
          

          【讨论】:

            【解决方案7】:
            public class ClassName implements Comparable<Object> {
            
                // Variables --------------------------------------------
                private double  comparedVariable; 
            
            
                // Constructor ------------------------------------------
                public ClassName (){}
            
            
                // Functions --------------------------------------------
                //returns the fuel weight
                public double getComparedVariable() {
                    return comparedVariable;
                }
            
            
                // Overrides --------------------------------------------
                @Override
                public int compareTo(Object o) {
            
                    ClassName classObject = (ClassName) o;
            
                    if (this.comparedVariable> classObject.getComparedVariable())
                        return 1; //make -1 to sort in decreasing order
                    else if (this.comparedVariable< classObject.getComparedVariable())
                        return -1;//make 1 to sort in decreasing order
                    else
                        return 0;
                }
            
            }
            

            【讨论】:

              【解决方案8】:
              public class player {
                   String Fname = "";
                  String Lname = "";
                  ArrayList<Card> cards= new ArrayList<Card> ();
                  public String getFname() {
                      return Fname;
                  }
              
                  public void setFname(String Fname) {
                      this.Fname = Fname;
                  }
              
                  public String getLname() {
                      return Lname;
                  }
              
                  public void setLastname(String Lname) {
                      this.Lname = Lname;
                  }
              
                  public ArrayList<Card> getCards() {
                      return cards;
                  }
              
                  public void setCards(ArrayList<Card> cards) {
                      this.cards = cards;
                  }
              
                  public player(String fname,String lname) {
                      this.Fname = fname;
                      this.Lname = lname;
                  }
                  
                  public void AddCard(Card card){
                      cards.add(card);
                  }
                  
                  public void showCards(){
                      System.out.println(""+Fname+" "+Lname+" holds the following cards");
                      for (int i=0;i<cards.size();i++)
                      {
                          System.out.print(cards.get(i).toString());
                      }
                      System.out.println();
                  }
                  
                  public void Sortcardsbyface()
                  {
                      for (int i = 0; i < cards.size() - 1; i++)
                      {
                          int j = i;
                          for (int k = i + 1; k < cards.size(); k++)
                          {
                              Card c = new Card();
                              if (c.toInt(cards.get(k).getFace()) < c.toInt(cards.get(j).getFace()))
                              {
                                  j=k;
                              }
              
                          }
              
                          Card temp = cards.get(j);
                          cards.set(j,cards.get(i));
                          cards.set(i,temp);
              
                      }
                      showCards();
                  }
              }
              
              
              /*
               * To change this license header, choose License Headers in Project Properties.
               * To change this template file, choose Tools | Templates
               * and open the template in the editor.
               */
              package pokegame;
              
              /**
               *
               * @author admin
               */
              public class Card {
                   private String face;
                  private char suit; 
              
                  Card(char suit,String face) {
                      this.suit = suit;
                      this.face = face;
                  }
              
                  Card() {
                      
                  }
              
                  public String getFace() {
                      return face;
                  }
              
                  public void setFace(String face) {
                      this.face = face;
                  }
              
                  public char getSuit() {
                      return suit;
                  }
              
                  public void setSuit(char suit) {
                      this.suit = suit;
                  }
                 
                  public String toString(){
                      return face+suit;  
                  }
                
                  
                  public int toInt(String face){
                      switch(face){
                          case "A":
                              return 1;
                          case "J":
                              return 11;
                          case "Q":
                              return 12;
                          case "K":
                              return 13;
                          case "2":
                              return 2;
                          case "3":
                              return 3;
                          case "4":
                              return 4;        
                          case "5":
                              return 5;        
                          case "6":
                              return 6;
                          case "7":
                              return 7;    
                          case "8":
                              return 8;    
                          case "9":
                              return 9;    
                          case "10":
                              return 10;    
                              
                              
                              
                              
                          default:
                              return 0;
                      }
                  }
                  
              }
              

              【讨论】:

                猜你喜欢
                • 2016-08-22
                • 2014-11-09
                • 2018-08-07
                • 2017-12-12
                • 1970-01-01
                • 1970-01-01
                • 2010-11-22
                • 2012-04-26
                • 1970-01-01
                相关资源
                最近更新 更多