【问题标题】:How to search an array of objects and then update a part of the object in java?如何在java中搜索对象数组然后更新对象的一部分?
【发布时间】:2015-04-01 02:15:00
【问题描述】:

我有一个对象数组。每个对象都是一个客户记录,即客户 ID (int)、名字 (String)、姓氏 (String) 和余额 (double)。

我的问题是我不应该有重复的客户记录,所以如果它们在文件中出现两次,我只需要更新他们的余额。我不知道如何搜索数组以确定我是否需要更新余额或在数组中创建新记录。

我觉得我应该在 get/setter 中执行此操作,但我不确定。

编辑:澄清“如果他们在文件中出现两次,我必须更新他们的余额。”我有一个我在记事本中制作的文件,它应该是一个客户列表,其中包含他们的所有信息。如果同一个客户出现两次,比如说第二天要买更多东西,我不应该为他们创建一个新对象,因为他们已经在数组中有一个对象和一个位置。相反,我应该取他们花费的金额,并将其添加到他们现有对象中已经存在的余额中。

edit2:我想我会给你一些我已经将值读入数组的代码。我基于我们在课堂上做的例子,但我们不需要更新任何东西,只需将信息存储到一个数组中并在需要时打印它。

public CustomerList(){
    data = new CustomerRecord[100]; //i'm only allowed 100 unique customers
    try {
        Scanner input = new Scanner(new File("Records.txt"));
        for(int i = 0; i < 100; ++i){
            data[i] = new CustomerRecord();
            data[i].setcustomerNumber(input.nextInt());
            data[i].setfirstName(input.next());
            data[i].setlastName(input.next());
            data[i].setTransactionAmount(input.nextDouble());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}   

【问题讨论】:

  • 你可以使用不同的数据结构吗?你能澄清一下“如果他们在文件中出现两次,我只需要更新他们的余额。”也是?

标签: java arrays object


【解决方案1】:

在这种情况下,您不应该使用 arraysSet 会更合适,因为根据定义,它没有重复条目。

您需要做的是在您的Customer 类中实现equals()hashCode() 方法,以便它们只使用id(或idname 字段)而不是balance

如果由于某种原因您需要使用数组,您有两种选择:

  • 对数组进行排序并使用二进制搜索来查找客户是否在那里,如果数组没有太大变化但您正在进行大量更新,这很好
  • 只需对数组进行线性扫描,检查每个条目以查看给定客户是否已经存在,如果存在则更新余额,否则将其添加为新条目

应该是这样的:

public void updateOrAdd(Customer cst) {
  boolean exists = false;
  for(Customer existing : array) {
    // !!! You need to implement your own equals method in the
    // customer so it doesn't take into account the balance !!!
    if(existing.equals(cst)) {
      exists = true;
      existing.updateBalance(cst.getBalance());
      break;
    }
  }
  if(!exists) {
    // add the cst to the array
  }
}

不同之处在于运行时,设置的解决方案平均为常数 O(1)(除非您错误地实现了您的 hashCode() 方法)。

【讨论】:

  • 看来op不能使用数组以外的任何数据结构
  • @KickButtowski 因此我回答的第二部分:-)
  • 是的,对不起,我刚要回答。我不允许使用其他任何东西,因为我还没有讨论过如何在课堂上使用集合。我们刚刚进入 oop,并且仍在试图弄清楚一切。所以如果我理解正确,我应该在读入客户 ID 后立即输入这些代码行吗?
  • @lilranford 是的,您从文件中读取了客户(这将创建一个客户对象),然后将其传递给该函数。
【解决方案2】:

假设你有一个Customer 数组:

Customer[] customers = new Customer[size];
... // fill the array with data

然后您将获得一个名为newCustomer 的新客户对象。您需要在您的数组中搜索newCustomer,如果它已经存在则更新它,或者如果它不存在则添加它。所以你可以这样做:

// Return, if it exists, a customer with id equal to newCustomer.getId()
Optional<Customer> existingCustomer =
    Arrays.stream(customers)
          .filter(c -> newCustomer.getId().equals(c.getId()))
          .findFirst();
if (existingCustomer.isPresent()) {
    // update the customer object with newCustomer information as appropriate
    Customer customer = existingCustomer.get();
    // assuming you have an updateBalance() method
    customer.updateBalance(newCustomer.amountSpent());
} else {
    // if the customer is not in the array already, add them to the current position
    customers[currentIndex] = newCustomer;
}

【讨论】:

    猜你喜欢
    • 2019-11-23
    • 1970-01-01
    • 2019-07-15
    • 2019-05-25
    • 2013-10-09
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多