【问题标题】:Android collections, which should i use? [closed]Android集合,我应该使用哪个? [关闭]
【发布时间】:2012-08-22 02:43:38
【问题描述】:

只是做了一个小安卓应用,我需要保存一个数据集合,不确定是否应该使用对象、数组、listarray、hashmap等。

它需要能够存储字符串和整数(例如名称、分数、类别、圈数)。

它需要能够存储可变数量的团队。

目前我尝试将其存储为对象时遇到问题,但它不会让我增加 score int 值。

我应该在这个实例中使用哪个集合,在其他实例中我应该在什么时候使用每个集合?

编辑

好的,这样做了,但是当我尝试访问/增加它时,我不断收到 NullPointerException。我只能假设它无法从 upScore 正确访问 team var

所以我的onCreate是这样的

public ArrayList<Team> teams;
public int currentTeam;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    currentTeam = 0;

    List<Team> teams = new ArrayList<Team>();

    teams.add(new Team("Team 1"));
    teams.add(new Team("Team 2"));

}

然后当按下按钮时调用 upScore。致命异常在这一行

public void upScore(int team_key) {
    teams.get(0).score++;
}

这是我的团队对象

class Team {
    public String name;
    public int score;
    public String category;
    public int turns;

    public Team (String teamName) {
        name = teamName;
    }
}

【问题讨论】:

  • 存储在 Team、Match、Play 类的对象中?
  • 我建议您先阅读一下,然后才能选择合适的集合。当您了解它们各自的优点时,您就会明白哪一个最适合您。

标签: java android arrays collections multidimensional-array


【解决方案1】:

创建您自己的类来表示可以保存您需要的数据的对象,例如:

class Team
{
    public String teamName;
    public int score;
    public String category;
    public int numberOfTurns;

    public Team(...){...} // the constructor
}

然后使用您想要的任何数据结构,例如,arraylist:

List<Team> list = new ArrayList<Team>();

向列表中添加元素:

list.add(new Team(...));

要增加列表中第一队的分数:

list.get(0).score++;

等等……

【讨论】:

    【解决方案2】:

    改变

    List&lt;Team&gt; teams = new ArrayList&lt;Team&gt;();

    teams = new ArrayList&lt;Team&gt;();

    见:Your declarations is hiding the member variables.

    【讨论】:

    • 请考虑使用私有变量而不是公共变量。
    • 接受的答案是 @Eng.Fouad 让我完成了 90% 的路程,但也为你提供了 rep++ :) thx!
    • 这应该是公认的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多