简体   繁体   中英

About ArrayList in java

I want to add some different types elements into the same index in ArrayList.For example:

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. 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 ?

You should create a model class named Account . Than define a list like 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.

Alexis C. is right (in the question's comments). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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