Arin Suryavanshi Arin Suryavanshi - 2 months ago 19
Java Question

Getting wrong values in HashMap

I have created HashMap for storing Brand:Car key value pair and inserted two car brands and their details.But on invoking .get(key) method I'm getting last stored values.

public class MapTest {
public static void main(String args[]) {

MapTest map=new MapTest();
map.test();

}
public void test() {
HashMap<String,Car> vehicle=new HashMap<>();
Details def=new Details();
Car car=new Car();
car.name="Mustang";
def.model="SportsRoof";
def.model_no=1969;
def.color="Blue";
car.features.add(def);
vehicle.put("Ford",car);
car.name="R8";
def.model="Coupe";
def.model_no=2009;
def.color="Black";
car.features.clear();
car.features.add(def);
vehicle.put("Audi",car);
System.out.println(vehicle.get("Ford").name);
System.out.println(vehicle.get("Ford").features.get(0).model);
System.out.println(vehicle.get("Ford").features.get(0).model_no);
System.out.println(vehicle.get("Ford").features.get(0).color);
}


Other Clsses

public class Car {
String name;
List<Details> features=new ArrayList<>();
public Car() {

}
}
public class Details {
String model;
int model_no;
String color;
public Details() {

}
}
}


Output
R8
Coupe
2009
Black

Answer

You're reusing the same car object over and over again. So, you've really not inserting different cars into the hashmap, you're inserting the same car object. However, an unintended side effect is that when you change, e.g. the name of the car, you change it everywhere in the map.

So, your code should look something like this:

HashMap<String,Car> vehicle = new HashMap<>();
Details def= new Details();
Car car = new Car();
car.name = "Mustang";
def.model = "SportsRoof";
def.model_no = 1969;
def.color = "Blue";
car.features.add(def);
vehicle.put("Ford",car);
// create a new Car object
car = new Car();
car.name = "R8";
def.model = "Coupe";
def.model_no = 2009;
def.color = "Black";
car.features.clear();
car.features.add(def);
vehicle.put("Audi",car);
Comments