从另一个类中的对象数组中访问单个对象

时间:2012-10-01 01:45:42

标签: java oop

好的,我有一个名为MonthlyReport的驱动程序类,它从2个不同的.dat文件中读取数据,一个包含有关帐户的信息,另一个包含有关客户的信息。在我的驱动程序类中,我创建了2个对象数组,分别存储帐户和客户的信息。问题是,一旦我将客户数据发送给客户类,我不确定如何指定哪个帐户属于每个客户,并且无法根据他们的身份修改帐户中的信息。

基本上,我想访问其客户的相应帐户对象,但我不知道如何从Customer类访问MonthlyReport中创建的对象。它更像是一个概念问题,我不一定需要代码,因为我需要一个设计建议。如果有助于回答问题,我可以添加一些代码。提前谢谢。

  public class MonthlyReport() {
       public static void main(String args[]){

             //reading in account data here

             Account a = new Account(accountNumber, accountType, balance, openingDates, aprAdjustment, feeAdjustment);
             accounts[i]=a;

             //reading in customer data here

             Customer c = new Customer(customerID, firstName, lastName, mailingAddress, emailAddress, flag, accountNum);
             customers[i]= c;

        }
   }

2 个答案:

答案 0 :(得分:2)

您可以编写包含两种数组数据类型的自定义类,并将.dat文件中的信息合并到此新类型的数组中

public class CustomerAccounts
{
    public Account[] Account {get; set;}
    public Customer Customer {get; set;}
}


public class MonthlyReport() {
   public static void main(String args[]){

         CustomerAccounts[] allData = new CustomerAccounts[totalCustomers];

         //Read in customers
         for (i = 0; i < totalCustomers; i++)
         {
               Customer c = new Customer(customerID, firstName, lastName, mailingAddress, emailAddress, flag, accountNum);
               CustomerAccounts customerAccount = new CustomerAccounts()'
               customerAccount.customer = c;
               allData [i] = customerAccount;

         }

         for (i = 0; i < totalAccounts; i++)
         {
              Account a = new Account(accountNumber, accountType, balance, openingDates, aprAdjustment, feeAdjustment);

              //Look up customer account belongs to to get index in all data array
              int index = lookupIndex();

              CustomerAccounts customerAccount = allData [index];
              int numberOfAccounts = customerAccount.accounts.count;
              allData [index].accounts[numberOfAccounts] = a;
         }
    }

答案 1 :(得分:1)

  

另一个问题是每个Customer可以拥有多个帐户。

假设CustomerAccount详细信息之间存在一对多关系,MonthlyReport应该包含对Map<Customer, List<Account>> data的引用。

附录:当您阅读客户文件并在Customer中累积Map个实例时,每个List<Account>最初都将为空。同时,将每个Customer添加到Map<AccountNumber, Customer> index。之后,在您阅读帐户文件时,您可以使用index为每个新帐户记录查找Customer,然后将其添加到该客户的List<Account>