关于java中的ArrayList

时间:2015-03-20 16:46:22

标签: java arraylist

我想在ArrayList中的同一个索引中添加一些不同的类型元素。例如:

List account= new ArrayList();
        String name;
        int number;
        float money;
        account.add(0,name);
        account.add(1,number); 
        account.add(2,money);

但是现在,我想把String name,int number和float money保存到同一个索引中。如何做?如果Arraylist不能。我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

  

我想把String name,int number和float money保存到   相同的指数。怎么做?

您应该创建一个名为Account的模型类。比定义List<Account>之类的列表。

 class Account{
  String name;
  int number;
  float money;
  // Constructor, Getter setter etc..... 
 }

 List<Account> list= new ArrayList<Account>();
 list.add(new Account("Name", 123, 50.0));     

比,帐户信息将在同一索引处的帐户实例处。您可以使用list.get(index)方法访问帐户数据。

答案 1 :(得分:1)

Alexis C.是对的(在问题的评论中)。 您必须使用类来表示帐户是什么。 然后,您将能够为所有帐户创建此类的实例。 示例:

class Account {
  String name;
  int number;
  float money;

  Account(String name, int number, float money) {
    this.name = name;
    this.number = number;
    this.money = money;
  }

}

// And somewhere else you'll want to use that class : 
List<Account> accounts = new ArrayList<>();
account.add(new Account("Account1", 1, 1f));
account.add(new Account("Account2", 2, 2f));
account.add(new Account("Account3", 3, 3f));

我建议你考虑学习基本的面向对象编程(即:组合,继承,多态)

希望这个例子有所帮助。

PS:在现实生活中,我建议使用BigDecimal类来处理金钱,因为float(和double)有精确问题。

相关问题