简体   繁体   中英

How do I loop / can I loop a hashmap put()?

I have an Arraylist with Vehicle properties and I needed to store them in a "car park slot", so I have decided to use HashMap to store vehicle slot with the vehicle registration, for example "1 = VEHICLE".

In my code I have it so that it adds an Integer and a Vehicle with a put statement after getting the required information from user input, it works for the first input but then after that it just gets replaced, how would I go about looping the put() or making a loop to add stuff into the map?

(I am also planning on making my HashMap creation and population a function that I call instead, this is just a temp thing until I figure this out or realise it's not possible.)

   public void carInfo(Vehicle tempVehicle, parkingSpace vehicle) {

        HashMap<Integer, Vehicle> hash_map = new HashMap<Integer, Vehicle>();

        array = new MCP();

        System.out.println("Please enter number plate: ");
        input = new Scanner(System.in);
        String plate = input.nextLine();

        System.out.println("Please enter car make: ");
        input = new Scanner(System.in);
        String make = input.nextLine();

        System.out.println("How would you best describe your Vehicle? ");
        System.out.println("(Car, Small Van, Tall Van, Long Van, Coach, Motorbike)");
        type = new Scanner(System.in);
        String type1 = input.nextLine();

            if (type1.equalsIgnoreCase(vehicleType.CAR.toString())) {
                tempVehicle.setPlate(plate);
                tempVehicle.setCarMake(make);
                tempVehicle.setVehicle(vehicleType.CAR);
                inv.createInvoice();
                tempVehicle.setInvoiceNumber(inv.invoiceNumber);

                array.addStandard(tempVehicle);

                hash_map.put(test++, tempVehicle);

                System.out.println(hash_map.toString());

I expect to add many inputs and get something like:

1 = Vehicle

2 = Vehicle

Instead I just get

1 = Vehicle

and then it will replace the first vehicle and then give out

2 = Vehicle

I have researched and realised it's because I only have 1 put so it just replaces the current thing mapped there, i'm just not sure how to loop it to fix this.

每次调用 carInfo 方法时都会创建一个新的 HashMap,因此 HashMap 始终只有一个条目,您可以将 HashMap 作为类的局部变量来解决这个问题。

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