简体   繁体   中英

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

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, eg 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);

In Java objects are stored based on references . You are initializing car variable only one time and assigning it to all keys of your Map .

You need to create different Car instances for different keys in your Map . And you need to create different instances of class Details too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM