I'm trying to make cars of a certain color go from one array to another. For example if I want all red cars to go to be displayed, I throw the red cars into another temporary array and they get displayed on the screen. How would I make this work? Here is my code:

//Where I declare the arrays
Car[] cars = new Car[11];
        Car[] tempCarsArray = new Car[100]; //What size should I make this?

for(int y=0; y<cars.length; y++){
   if(cars[y].getColor()=="Red"){
    	tempCarsArray[y] = new Car(cars[y].getColor(), cars[y].getMake());
    	textView.setText(tempCarsArray[randomNumber].getColor(), tempCarsArray.getMake(), tempCarsArray[y].getModel(), tempCarsArray[y].getDescription());
    				n = tempCarsArray.length;
    			}
    		}

Don't compare Strings using the == operator; when used with primitives it compares values whereas when used with reference types it compares references. If you need a logical comparison (comparing values), use the `equals()' method for objects (which falls back to reference comparison if the object in consideration doesn't override the `equals()' method of the Object class).

Also, why are you creating a new 'Car' object just for display purposes? A simple loop over the existing Car array should do the trick. Regarding the size of the new temporary array, is it really required that you use an array? Whenever acceptable, using a List instead of an array is much more easier to work with and flexible. Something simple like this should do the trick:

final StringBuilder buf = new StringBuilder();
for(final Car car : cars) {
  buf.append('Color: ').append(car.getColor()).append('\n');
}
textView.setText(buf.toString());
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.