如何在ArrayList中判断添加/替换元素,避免数组越界异常
Solution to Build carsList with Add/Set Logic
First, let's break down the core rule that will guide when to use add() vs set()—this approach avoids IndexOutOfBoundsException while matching your exact requirements:
For each car in a customer's car list (at position i, starting from 0):
- If
iis less than the current size ofcarsList: Useset(i, car)to replace the existing element at that index. - If
iis equal to or greater than the current size ofcarsList: Useadd(car)to append the new car to the end of the list.
This works because:
set()is only called wheniis a valid index (ArrayList indices range from 0 tosize()-1), so no out-of-bounds errors.add()extends the list when there's no existing element at positioni, which is safe by design.
Step-by-Step Implementation
Here's a complete code example (assuming you have standard Customer and Car classes):
import java.util.ArrayList; import java.util.List; public class CarListBuilder { public static void main(String[] args) { // Example customer data (replace with your actual list) Customer customer1 = new Customer("John", "Doe", new Car[]{ new Car("Toyota", "Camry", "Blue"), new Car("Honda", "Civic", "Red") }); Customer customer2 = new Customer("Jane", "Smith", new Car[]{ new Car("Ford", "F-150", "Black"), new Car("Chevrolet", "Malibu", "White"), new Car("Tesla", "Model 3", "Silver") }); Customer customer3 = new Customer("Bob", "Brown", new Car[]{ new Car("BMW", "X5", "Gray"), new Car("Mercedes", "C-Class", "Black") }); List<Customer> customers = List.of(customer1, customer2, customer3); List<Car> carsList = new ArrayList<>(); // Build the carsList per your requirements for (Customer customer : customers) { Car[] customerCars = customer.getCars(); for (int i = 0; i < customerCars.length; i++) { Car currentCar = customerCars[i]; if (i < carsList.size()) { // Replace existing element at index i carsList.set(i, currentCar); } else { // Append new element since index i doesn't exist yet carsList.add(currentCar); } } } // Verify the result (optional) for (Car car : carsList) { System.out.printf("%s %s (%s)%n", car.getMake(), car.getModel(), car.getColour()); } } // Dummy classes for context static class Customer { private String firstName; private String lastName; private Car[] cars; public Customer(String firstName, String lastName, Car[] cars) { this.firstName = firstName; this.lastName = lastName; this.cars = cars; } public Car[] getCars() { return cars; } } static class Car { private String make; private String model; private String colour; public Car(String make, String model, String colour) { this.make = make; this.model = model; this.colour = colour; } public String getMake() { return make; } public String getModel() { return model; } public String getColour() { return colour; } } }
Walkthrough of the Example Execution
Let's confirm this matches your requirements:
- First Customer (2 cars):
carsListstarts empty. Both cars are added, resulting in[Toyota Camry, Honda Civic].
- Second Customer (3 cars):
- First two cars replace the existing elements:
[Ford F-150, Chevrolet Malibu]. - Third car is appended, resulting in
[Ford F-150, Chevrolet Malibu, Tesla Model 3].
- First two cars replace the existing elements:
- Third Customer (2 cars):
- First two cars replace the first two elements:
[BMW X5, Mercedes C-Class]. - The third element from the second customer remains, so final list is
[BMW X5, Mercedes C-Class, Tesla Model 3].
- First two cars replace the first two elements:
This logic scales to any number of customers or cars per customer without errors.
内容的提问来源于stack exchange,提问作者Jones5672
相关产品推荐
相关产品推荐

