This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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:
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.
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.