At the moment I have an array constructed like this:
Car[] garage = new Car[5];
garage[0] = new Car("Ford", "Focus", "S301 ABN");
garage[1] = new Car("Opel", "Astra", "WA55 AAP");
garage[2] = new Car("Ford", "Explorer", "L66 4ABE");
garage[3] = new Car("Dodge", "Viper", "FA55 SAM");
garage[4] = new Car("Ferrari", "F50", "SAS3 47S");
However, I need the size of the array to be set by a user defined value which comes from a JComboBox. I’ve got the JComboBox setting the value working but it throws an ArrayIndexOutOfBoundsException because elements exist that aren’t within the array index bounds. So my question is, what way should I go about adding the elements to the array after the user selects the size of the array?
Import
java.util.ArrayList, and use the ArrayList data structure instead of a normal array.To do the same thing your code you posted, you’d use code like something like this:
To get the nth element of the garage, use
garage.get(n).