简体   繁体   English

我如何循环/我可以循环哈希图 put() 吗?

[英]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".我有一个带有 Vehicle 属性的 Arraylist,我需要将它们存储在“car park slot”中,所以我决定使用 HashMap 来存储带有车辆注册的车辆槽,例如“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?在我的代码中,我有它,以便它在从用户输入获取所需信息后添加一个 Integer 和一个带有 put 语句的 Vehicle,它适用于第一个输入,但之后它刚刚被替换,我将如何循环put() 还是创建一个循环以将内容添加到地图中?

(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.) (我还计划让我的 HashMap 创建和填充成为一个我调用的函数,这只是一个临时的事情,直到我弄清楚或意识到这是不可能的。)

   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.我已经研究并意识到这是因为我只有 1 个 put 所以它只是替换了映射到那里的当前事物,我只是不确定如何循环它来解决这个问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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