gpt4 book ai didi

java - 在对象中查找值时使用 ArrayList.indexOf

转载 作者:行者123 更新时间:2023-12-01 16:44:13 26 4
gpt4 key购买 nike

我有一个分支类,其中包含客户对象的数组列表。在分支类中,我想为给定的客户名称添加交易,但首先我想检查客户是否存在,然后添加交易。

private boolean customerExists(String customerName) {
for (int i = 0; i < customers.size(); i++) {
if(customers.get(i).getCustomerName().equalsIgnoreCase(customerName)) {
return true;
}
}
return false;
}


private int customerPosition(String customerName) {
for (int i = 0; i < customers.size(); i++) {
if(customers.get(i).getCustomerName().equalsIgnoreCase(customerName)) {
return i;
}
}
return -1;
}



public void addTransaction(String customerName, Double transactionValue) {
if(customerExists(customerName) == false) {
System.out.println("Customer with name " + customerName + " not found");
} else {
customers.get(customerPosition(customerName)).addTransaction(transactionValue);
}
}

我知道这段代码可以工作,但是我意识到我必须对数组列表进行两次循环来检查它是否存在,并获取它的位置。这似乎效率低下

我知道 indexOf 方法在 addTransaction 中很有用,但如果我要查找对象内的特定值,我不确定如何使用它,而不是对象本身,即我不是在寻找 Customer 对象,而是在对象内寻找值。任何建议将不胜感激。

编辑:谢谢大家,这些答案非常棒。

最佳答案

一般来说,除了循环遍历列表来查找值之外,您不能做任何更好的事情。

在代码重复方面,将 customerExists 的正文替换为:

return customerPosition() >= 0;

并且,在 addTransaction() 中,将 customerPosition() 的结果存储在变量中,并使用 thatVariable >= 0 而不是调用customerExists()

如果您使用的是 Java 8+,则可以使用流:

Optional<Customer> cust = customers.stream().filter(c -> c.getCustomerName().equals(customerName)).findFirst();

那么您根本不必担心使用索引。

关于java - 在对象中查找值时使用 ArrayList.indexOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55890056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com