如何访问Object实例的数组索引

时间:2011-05-05 15:42:11

标签: java

美好的一天!

我想知道如何访问Object实例的数组索引。

我的代码如下:

public class PokerPlayer {

    private String name = null;
    private Card [] cardsOnHand = new Card[5]; 

    //getter and setter
}

我想要的是访问cardsOnHandArray [index],以便我可以在另一个类上调用它并设置每个索引的值...

public class PokerGame {
      public static void main (String [] Args){
      PokerPlayer players []= new PokerPlayer[4];
      for(PokerPlayer player : players){
          for(int i =0; i<5; i++){
            //ACCESS cardsOnHand index i and store something on it...
          }
        }
    }
}

任何建议都将受到高度赞赏。我怎样才能改进我的OO设计?提前谢谢

6 个答案:

答案 0 :(得分:4)

public class PokerPlayer {
...
public Card getCard(int index) {
  return this.cardsOnHand[index];
}

public void setCard(int index, Card card) {
  this.cardsOnHand[index] = card;
}
...
}

然后使用:

player.getCard(i);
player.setCard(i,new Card());

答案 1 :(得分:3)

答案 2 :(得分:1)

你可以这样做:

for(PokerPlayer player : players){
          for(int i =0; i<5; i++){
            Card[] cards= player[i].getCardsOnHand();
            cards[i] = new Card();
          }
        }

答案 3 :(得分:1)

答案 4 :(得分:1)

答案 5 :(得分:1)

假设您的PokerPlayercardsOnHand数组的getter:

public class PokerGame {
      public static void main (String [] Args){
      PokerPlayer players []= new PokerPlayer[4];
      for(PokerPlayer player : players){
          for(int i =0; i<5; i++){
                player.getCardsOnHand()[i] = new Card();
          }
        }
    }
}

但是,我认为更好的解决方案是添加方法

public void setCard(Card card, int index) {
    assert index < 5;
    cardOnHands[index] = card
}

PokerPlayer