You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 i is less than the current size of carsList: Use set(i, car) to replace the existing element at that index.
  • If i is equal to or greater than the current size of carsList: Use add(car) to append the new car to the end of the list.

This works because:

  • set() is only called when i is a valid index (ArrayList indices range from 0 to size()-1), so no out-of-bounds errors.
  • add() extends the list when there's no existing element at position i, 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:

  1. First Customer (2 cars):
    • carsList starts empty. Both cars are added, resulting in [Toyota Camry, Honda Civic].
  2. 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].
  3. 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].

This logic scales to any number of customers or cars per customer without errors.

内容的提问来源于stack exchange,提问作者Jones5672

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:24:32