Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an object to an Array of a custom class [duplicate]

Tags:

java

arrays

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;
like image 1000
Dangerosking Avatar asked May 01 '12 15:05

Dangerosking


People also ask

How do you add an object to an array?

To achieve this, we'll use the push method. As you can see, we simply pass the obj object to the push() method and it will add it to the end of the array. To add multiple objects to an array, you can pass multiple objects as arguments to the push() method, which will add all of the items to the end of the array.

Can ArrayList store duplicate?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

Does array allow duplicate values?

Using the has() method In the above implementation, the output array can have duplicate elements if the elements have occurred more than twice in an array. To avoid this and for us to count the number of elements duplicated, we can make use of the use() method.


2 Answers

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);
like image 173
Petar Minchev Avatar answered Sep 18 '22 07:09

Petar Minchev


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.
like image 45
Pat Murray Avatar answered Sep 18 '22 07:09

Pat Murray