I have an array cars[i] which stores info about cars using NewCar(String model, int price, String color, int year) class and UsedCar(String model, int year, int price, boolean rusty) class.
Now i have another class called CarDealerShip .....in which i need to implement a method that takes in parameter color for cars and returns all cars that have a particular color (as stated int he parameter) here is the method below.....i am unable to implement it:
public Car getCars(String color)
How will i do that?? can anyone help me??
author and iconoclast
Well, one way to do it would be to create a collection -- say a java.util.ArrayList -- and then write a for loop whiich iterates over the array of Cars and stores each one of the approriate color into the collection. Then at the end, you can use the collection's "toArray()" method to create an array contining just those Cars ( you'll have to pass a new Car as an argument to toArray, or it will return an Object.
....i am done with the asignment...its just that i cant figure out this last method implementation. Any help will be appreciated. Thank you.
Joined: Apr 16, 2004
Originally posted by farrukh zaheen: ...but what i dont understand is....how will i compare the color in the IF statement and collect all cars with the same color.
The color is represented by a String, so in this case, you will be comparing Strings. Remember, you do not want to use the == operator to do this, you'll want to look at the equals() method.
Now, to continue using the ArrayList scheme, you can create a temporary ArrayList which will represent all cars found to be the same color (as you find a car which matches the color, add it to the ArrayList). Once your loop is finished, you return this temporary ArrayList.