-1

For some reason I cannot get my iteration working. I have two classes, Cars and Garage. I have Map<Integer, Cars> cars = newHashMap<>(); within the Garage class and I want to iterate through all the Car objects in Map looking for a value of "Ford" and then print it out.

Any help/explanations would be great as very much a newbie.

private String model;
model = "Ford";

public void carMake() {
    for (Cars eachCar : cars.values()) {
        if (cars.containsValue(model)) {
            System.out.println("It is a ford");
        }
    }     
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Scotty
  • 45
  • 1
  • 7

1 Answers1

1

Try it, supposing that class Car has a getModel() function that returns the car Model (Ford):

public void carMake() {
    for(Cars eachCar : cars.values()) {
        if("Ford".equals(eachCar.getModel()) {
             System.out.println("It is a ford");
        }
    }
}

In your code each interaction checks if your map (that contains Cars value) contains your model (that is a String). Even if you suppose that your model variable is a Car with model value = "Ford", each interaction you are checking the entire map, not the current value.

Glim
  • 361
  • 1
  • 10