【问题标题】:Accessing an Array List contents in a different class访问不同类中的数组列表内容
【发布时间】:2014-05-18 11:22:50
【问题描述】:

我在一个类中有一个卡片对象hand 的数组列表。这个数组列表hand 必须保持私密。在另一个类中,我需要访问此数组列表中的 Card 对象并在每个对象上调用 toString() 方法以将它们转换为可读的卡片名称。所以我在包含返回手的数组列表hand 的类中创建了一个getHand() 方法。但是我现在如何访问手中的个人牌?因为如果我做 hand.get(i).getSuit() 例如,它不能这样做,因为 hand 是私有的。任何建议表示赞赏。

A类:

private ArrayList<Card> hand; 

public Player()
{       
    ArrayList<Card> hand = new ArrayList<Card>();
}
    ...

B类:

...
public String toString(){
    this.getSuit();
    this.getValue();
    //code to convert numerical suit and value to a string
    //this method will use a Card object
    //as an implicit parameter

C类:

Player p = new Player();
p.getHand();
//next I need to indicate that each card
//within hand needs to be called with
//the toString method? This is my question

【问题讨论】:

  • 你有没有尝试像你描述的那样做?,而不是hand使用getHand()
  • 我不知道你为什么不能那样做,也不知道你为什么在Player的构造函数中使用局部变量hand

标签: java arrays


【解决方案1】:

最好避免返回 Player 类的成员变量(这违反了得墨忒耳法则)。

这里有一些替代方案:

class Player implements Iterable<Card> {
    ...
    public Iterator<Card> iterator() {
        return cards.iterator();
    }
    ...
}

另一种选择:

interface CardVisitor {
    public void visitCard(Card card);
}

class Player {
    ...
    public void visitCards(CardVisitor visitor) {
        for (Card card : cards)
            visitor.visitCard(card);
    }
    ...
}

class CardPrinter {
    public String toString() {
        StringBuilder sb = new StringBuilder();
        ...
        CardVisitor visitor = new CardVisitor() {
            public void visitCard(Card card) {
                sb.append(card.toString()); // or something like that
            }
        }
        player.visitCards(visitor);
        ...
        return sb.toString();
    }
}

还有很多方法可以解决这个问题,但我想你明白我的意思了。

【讨论】:

    【解决方案2】:

    p.getHand() 将返回 ArrayList&lt;Card&gt;,因此您只需遍历它并打印每个 Card 对象的 .toString()

    Player p = new Player();
    ArrayList<Card> cards = p.getHand();
    
    for (Card card : cards)
    {
        System.out.println(card.toString());
    }
    

    您必须调用getHand() 而不是直接使用ArrayList,因为getHand() 是公共getter,其他类可以调用它,但hand 是私有的,它只能在ClassA 内部访问而不使用任何getter 或二传手。

    另外,您的 Player 构造函数应该如下所示

    public Player()
    {       
        this.hand = new ArrayList<Card>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2014-03-05
      相关资源
      最近更新 更多