简体   繁体   English

关于Java中的ArrayList

[英]About ArrayList in java

I want to add some different types elements into the same index in ArrayList.For example: 我想在ArrayList的同一索引中添加一些不同类型的元素,例如:

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

But now , i want to take String name , int number and float money save into the same index.How to do it ?If Arraylist can't. 但是现在,我想将String name,int number和float money保存到同一索引中。如何做到这一点?如果Arraylist无法。 How can i do act this function? 我该如何执行此功能?

i want to take String name , int number and float money save into the same index.How to do it ? 我想将字符串名称,整数和浮点数保存到同一index.How呢?

You should create a model class named Account . 您应该创建一个名为Account的模型类。 Than define a list like List<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));     

Than, account information will be at account instance at same index. 然后,帐户信息将位于相同索引处的帐户实例处。 You can access the Account data using list.get(index) method. 您可以使用list.get(index)方法访问帐户数据。

Alexis C. is right (in the question's comments). 亚历克西斯·C(Alexis C.)正确(在问题的评论中)。 You'll have to use a class to represents what is an account. 您必须使用一个类来代表什么是帐户。 Then you'll be able to create instances of this class for all accounts. 然后,您将可以为所有帐户创建此类的实例。 Example : 范例:

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));

I suggest you to consider learning basic object oriented programming (ie:Composition, Inheritance, Polymorphism) 我建议您考虑学习基本的面向对象编程(即:组成,继承,多态)

Hope this example help. 希望本示例对您有所帮助。

PS : In a real life application, I would recommend the use of the BigDecimal class to handle money, as float (and double) have precision problems. PS:在现实生活中的应用中,我建议使用BigDecimal类来处理金钱,因为float(和double)存在精度问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM