13

Im a beginner to Java and I'm trying to create an array of a custom class. Let say I have a class called car and I want to create an array of cars called Garage. How can I add each car to the garage? This is what I've got:

car redCar = new Car("Red");
car Garage [] = new Car [100];
Garage[0] = redCar;
Kai
  • 38,985
  • 14
  • 88
  • 103
Dangerosking
  • 438
  • 3
  • 12
  • 23
  • 3
    Naming conventions: variables start with lower case and objects with upper case: `Car redCar = ...`, `Car[] garage = ...`, `garage[0]` etc. – assylias May 01 '12 at 16:00

3 Answers3

29

If you want to use an array, you have to keep a counter which contains the number of cars in the garage. Better use an ArrayList instead of array:

List<Car> garage = new ArrayList<Car>();
garage.add(redCar);
Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
  • 1
    And how can I get a particular car in the garage? Like how do I get the first car added? – Dangerosking May 01 '12 at 16:01
  • +1 for the list suggestion :). The next step would be to implement `equals()` and `hashCode()` and use a `Set` (since it might not make much sense for exactly the same car to be in a garage twice :) ). – Thomas May 01 '12 at 16:01
  • @Dangerosking - Use `garage.get(0)` – Petar Minchev May 01 '12 at 16:02
  • *"And how can I get a particular car in the garage?"* http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html – CodeClown42 May 01 '12 at 16:03
  • Can the arraylist be used in a abstract class? Just like the array, I can create it but I can't add an object to it. – Dangerosking May 01 '12 at 18:24
12

The array declaration should be:

Car[] garage = new Car[100];

You can also just assign directly:

garage[1] = new Car("Blue");
CodeClown42
  • 11,194
  • 1
  • 32
  • 67
6

If you want to create a garage and fill it up with new cars that can be accessed later, use this code:

for (int i = 0; i < garage.length; i++)
     garage[i] = new Car("argument");

Also, the cars are later accessed using:

garage[0];
garage[1];
garage[2];
etc.
Pat Murray
  • 4,125
  • 7
  • 28
  • 33