Problems with hashmap getordefault in java

Asked

Viewed 92 times

1

I have a hashmap problem, in JAVA.

I’m trying to create a program that reads data from a car, save these cars in an Arraylist and organize, by the manufacturer(that would be the key) the cars of your brand.

public static void main(String[] args) {
    //Value to user answers
    String resp = "s";
    //New list of Car objects
    List<Car> carros = new ArrayList<>();

    try(Scanner input = new Scanner(System.in)){
      while(resp.equalsIgnoreCase("s")){

        //Create a car for every answer
        Car car = new Car();
        String resposta;
        System.out.println("Empresa do carro: ");
        resposta = input.next();
        car.setManufacturerCar(resposta);
        System.out.println("Modelo do carro: ");
        resposta = input.next();
        car.setModelCar(resposta);
        System.out.println("Quantas portas há no carro?");
        resposta = input.next();
        car.setDoorsCar(resposta);
        System.out.println("Marcha manual ou automatica?");
        resposta = input.next();
        car.setGearshift(resposta);

        //Add a car to arraylist
        carros.add(car);

        System.out.println("Deseja continuar?");
        resp = input.next();
      }
    }

    //Map that will be organized
    Map<String, List<Car>> mapCarros = new HashMap<>();

    for(Car c : carros){

      mapCarros.put(c.getManufacturerCar(), carros);

    }

    System.out.println(mapCarros);

}

When I tried to run, saving 2 beetles and a Focus, it saves all cars in all manufacturers:

{VW=[Car{manufacturerCar=VW, modelCar=FUSCA, doorsCar=2, gearshift=MANUAL}, Car{manufacturerCar=VW, modelCar=FUSCA, doorsCar=2, gearshift=MANUAL}, Car{manufacturerCar=FORD, modelCar=FOCUS, doorsCar=4, gearshift=AUTOMATICO}], FORD=[Car{manufacturerCar=VW, modelCar=FUSCA, doorsCar=2, gearshift=MANUAL}, Car{manufacturerCar=VW, modelCar=FUSCA, doorsCar=2, gearshift=MANUAL}, Car{manufacturerCar=FORD, modelCar=FOCUS, doorsCar=4, gearshift=AUTOMATICO}]}

1 answer

1


You’re saving the list carros for all tags. Instead create one for each:

for (Car c : carros){
  List<Car> lista;
  if (mapCarros.containsKey(c.getManufacturerCar())) {
    lista = mapCarros.get(c.getManufacturerCar());
  } else {
    lista = new ArrayList<>();
    mapCarros.put(c.getManufacturerCar(), lista);
  }

  lista.add(c);
}
  • In case you have created a list of Car objects, compare if the Key is the same as the car name, if the list is named after the manufacturer, if not it creates an Arraylist within the list and adds a new one? Check? Anyway it worked! Thank you very much.

  • If it is received the list reference, after all Objects in Java are shared by reference in the assignment. If it does not exist it creates a new list

Browser other questions tagged

You are not signed in. Login or sign up in order to post.