
本教程旨在解决在java `arraylist
在Java应用程序开发中,我们经常需要处理集合数据,其中一种常见场景是管理一个包含一维数组的列表,例如 ArrayList<int[]>。当每个一维数组代表一个实体(如商品ID和数量),并且我们需要根据某个特定索引的值(如商品ID)来判断元素是否存在,如果存在则更新其关联值(如数量),否则添加新元素时,需要特别注意Java集合的特性和对象引用。
初学者在处理这类问题时,常会遇到以下几个误区:
ArrayList.contains()的误用: 尝试使用ord.contains(Order[0] == idConso)这样的表达式来检查元素是否存在。
对象引用的混淆: 在循环外部声明并初始化数组对象(例如 int[] Order = new int[2];),然后在每次迭代中修改并添加到列表中。
立即学习“Java免费学习笔记(深入)”;
为了正确地实现根据ID查找、更新或添加元素,我们需要采取迭代的方式,并确保每次添加的都是独立的数组对象。
核心思想是遍历ArrayList中的每一个int[]元素,检查其第一个索引的值(商品ID)是否与待处理的ID匹配。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class OrderManager {
// ... (其他辅助方法如 getUserIntOrSpecificInputV2, NAMES 保持不变) ...
public static void getOrder(ArrayList<int[]> ord) {
String userInput;
int idConso = 0;
int nbrConso = 0;
// 首次获取用户输入
userInput = getUserIntOrSpecificInputV2("Entrez le N° de consommable "
+ "ou Q(Quitter) ", "Q", 1, NAMES.length);
do {
if (userInput.equalsIgnoreCase("Q")) {
System.out.println("Fin de Programme, Au Revoir");
System.exit(-1);
} else {
idConso = Integer.parseInt(userInput);
}
userInput = getUserIntOrSpecificInputV2("Nombre de consommations pour " + NAMES[idConso - 1] + " ? /A(Annuler) /Q (Quitter)", "AQ", 1, 5000);
if (userInput.equalsIgnoreCase("Q")) {
System.out.println("Fin de Programme, Au Revoir");
System.exit(-1);
} else if (userInput.equalsIgnoreCase("A")) {
// 如果用户选择取消,则跳过本次订单处理,直接进入下一轮商品ID输入
userInput = getUserIntOrSpecificInputV2("Entrez le N° de consommable ou Q(Quitter) V (Valider le ticket) ", "QV", 1, NAMES.length);
continue; // 跳过当前循环的剩余部分,直接进入下一次do-while循环
}
nbrConso = Integer.parseInt(userInput);
// 标志位,用于判断是否找到并更新了现有订单
boolean foundAndUpdated = false;
// 遍历现有订单列表,检查商品ID是否存在
for (int[] existingOrder : ord) {
if (existingOrder[0] == idConso) {
// 找到匹配的商品ID,更新其数量
existingOrder[1] += nbrConso;
System.out.println("更新订单: " + NAMES[idConso - 1] + ", 新数量: " + existingOrder[1]);
foundAndUpdated = true;
break; // 找到并更新后,即可退出循环
}
}
// 如果没有找到匹配的商品ID,则添加新订单
if (!foundAndUpdated) {
// 关键点:在每次需要添加新订单时,都创建一个新的 int[] 数组对象
int[] newOrder = new int[2];
newOrder[0] = idConso;
newOrder[1] = nbrConso;
ord.add(newOrder);
System.out.println("添加新订单: " + NAMES[idConso - 1] + ", 数量: " + nbrConso);
}
// 获取下一个操作的用户输入
userInput = getUserIntOrSpecificInputV2("Entrez le N° de consommable ou Q(Quitter) V (Valider le ticket) ", "QV", 1, NAMES.length);
} while (!userInput.equalsIgnoreCase("V")); // 当用户输入不是"V"时继续循环
// 打印最终订单列表
System.out.println("\n--- 最终订单详情 ---");
for (int[] item : ord) {
System.out.println(Arrays.toString(item) + " - " + NAMES[item[0] - 1] + " x " + item[1]);
}
System.out.println("总商品种类数: " + ord.size());
}
public static void main(String[] args) {
ArrayList<int[]> orderList = new ArrayList<>();
getOrder(orderList);
}
// 辅助方法(getUserIntOrSpecificInputV2, checkTable, NAMES)保持原样
final static String NAMES[] = {
"Spa reine 25 ", "Bru plate 50", "Bru pét 50", "Pepsi", "Spa orange",
"Schweppes Tonic", "Schweppes Agr", "Ice Tea", "Ice Tea Pêche", "Jus d'orange Looza", "Cécémel",
"Red Bull", "Petit Expresso", "Grand Expresso", "Café décaféiné ", "Lait Russe ", "Thé et infusions",
"Irish Coffee ", "French Coffee ", "Cappuccino", "Cécémel chaud", "Passione Italiano", "Amour Intense",
"Rhumba Caliente ", "Irish Kisses ", "Cuvée Trolls 25", "Cuvee Trolls 50", "Ambrasse-Temps 25", "Ambrasse-Temps 50 ",
"Brasse-Temps Cerises 25", "Brasse-Temps Cerises 50", "La Blanche Ste Waudru 25", "Blanche Ste Waudru 50",
"Brasse-Temps citr 25", "Brasse-Temps citr 50", "Spaghetti Bolo ", "Tagl Carbonara", "Penne poulet baslc ",
"Tagl American", "Tagl saum"
};
public static String getUserIntOrSpecificInputV2(String msg, String expectedAnsw, int min, int max) {
int intInput = 0;
String strAnsw = "";
Scanner sc = new Scanner(System.in);
do {
System.out.println(msg);
if (sc.hasNextInt()) {
intInput = sc.nextInt();
if (intInput >= min && intInput <= max) {
return Integer.toString(intInput);
} else {
System.out.println("La saisie doit être comprise entre " + min + " et " + max);
}
} else {
strAnsw = sc.next();
if (strAnsw.length() == 1 && expectedAnsw.toUpperCase().contains(strAnsw.toUpperCase())) {
return strAnsw.toUpperCase();
} else {
System.out.println("Erreur de saisie : caractères autorisés " + expectedAnsw);
}
}
} while (true);
}
public static boolean checkTable(int[] table, int numberCheck) {
for (int i = 0; i < table.length; i++) {
if (table[i] == numberCheck) {
return true;
}
}
return false;
}
}对象引用是关键: 在Java中,理解对象引用和值传递对于正确管理集合至关重要。当向ArrayList添加对象时,实际上是添加了该对象的引用。
自定义类优于原始数组: 对于更复杂的实体,建议创建自定义的类(例如ProductOrder),而不是直接使用int[]。自定义类可以包含有意义的字段名(如productId和quantity),提高代码的可读性和可维护性。此外,自定义类可以重写equals()和hashCode()方法,从而使ArrayList.contains()、ArrayList.remove()以及其他基于内容比较的集合操作更加直观和高效。
// 示例:使用自定义ProductOrder类
class ProductOrder {
int productId;
int quantity;
public ProductOrder(int productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
// 重写equals和hashCode方法以支持基于内容的比较
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductOrder that = (ProductOrder) o;
return productId == that.productId; // 仅根据productId判断相等
}
@Override
public int hashCode() {
return Objects.hash(productId);
}
@Override
public String toString() {
return "ProductOrder{" +
"productId=" + productId +
", quantity=" + quantity +
'}';
}
}
// 在getOrder方法中使用:
// ArrayList<ProductOrder> ord = new ArrayList<>();
// ...
// ProductOrder newProduct = new ProductOrder(idConso, nbrConso);
// int index = ord.indexOf(newProduct); // 如果重写了equals,可以直接查找
// if (index != -1) {
// ord.get(index).quantity += nbrConso;
// } else {
// ord.add(newProduct);
// }输入验证与用户体验: 原始代码中的getUserIntOrSpecificInputV2方法是良好的实践,它提供了健壮的用户输入验证。在实际应用中,应始终确保用户输入符合预期,并提供友好的提示。
在Java中处理ArrayList<int[]>这类复杂数据结构时,理解其底层机制至关重要。避免ArrayList.contains()的误用,并正确处理对象引用,是确保数据逻辑正确性和一致性的关键。通过迭代查找、使用标志位以及在必要时创建新的独立对象,可以有效地实现元素的检查、更新和新增操作。对于更复杂的业务场景,采用自定义类并重写equals()和hashCode()方法将是更专业和可维护的选择。
以上就是Java中管理一维数组列表:检查、更新与新增元素的高效策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号