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;
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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With