【问题标题】:Java - acces object methods trough an array indexJava - 通过数组索引访问对象方法
【发布时间】:2016-12-13 13:14:12
【问题描述】:

我在从数组中的对象访问方法时遇到问题。我正在尝试创建一个纸牌游戏。在创建卡片对象的那一刻,我将它们推送到 Arraylist 中。现在,当我在这个数组中获得例如 5 个卡片对象时,我想访问索引为 [0] 的卡片的方法,但我不知道如何。这是代码:

    public static void main(String[] args) {
      Main main = new Main();
      //creates new card
      Card FireElemental = new Card("Fire Elemental");

      // adds card to array
      main.player2FieldCards.add(FireElemental);

      // Now to access it's methods, the example below is not working but 
      // to give an example of what I want.
      main.player2FieldCards.get(0).SomeMethod();
}

【问题讨论】:

  • 应该可以。可以分享CardMain的代码吗?
  • 很可能,您将player2FieldCards 声明为ArrayList,但没有泛型类型。 ArrayList player2FieldCards = new ArrayList()之类的,如果是真的,你应该改成:List<Card> player2FieldCards = new ArrayList<>()
  • 你应该转换它 ((yourClass)main.player2FieldCards.get(0)).SomeMethod();
  • 您有一个名为main() 的方法、一个名为Main 的类和一个名为main 的类的实例。这令人困惑;不要这样做——它会在以后产生问题。将类重命名为CardDeck,将实例重命名为playerHand。只需确保不同的事物具有不同的名称,以便它们易于识别。

标签: java arrays object methods


【解决方案1】:

如果您的意思是,在您的情况下,“Main”包含 arraylist,也许您忘记将其设为通用。您需要添加ArrayList<Card> 而不是纯ArrayList,因为没有泛型,您存储对象元素并且为了调用 Card 对象上的方法,您需要先将其转换为 Card。

((Card)main.player2FieldCards.get(0)).SomeMethod();

【讨论】:

  • 是的!就是这样!感谢您的帮助和快速回复!
【解决方案2】:

我认为你的逻辑部分出错了。您的解决方案可能(或不会)有很多问题。 Main 类定义中的 List 可能不是通用的。你想做的事情应该是这样的。主类应该是这样的。

public class Main {
    List<Card> player2FieldCards; //Must not be List player2FieldCards;

    public Main() {
        player2FieldCards = new ArrayList<>();
    }

    public static void main(String args[]) {
        //Rest of you main method code goes here
    }
}

应该有另一个名为Card 的类。看起来应该是这样的。

class Card {
    // Fields declarations 

    // Methods declarations 

    public void SomeMethod() {

    }
}

如果您对类的定义有些相似。然后事情应该按预期工作。如果不是,请指出并回复我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2016-04-01
    • 2020-07-19
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多