[英]How do I loop / can I loop a hashmap put()?
我有一個帶有 Vehicle 屬性的 Arraylist,我需要將它們存儲在“car park slot”中,所以我決定使用 HashMap 來存儲帶有車輛注冊的車輛槽,例如“1 = VEHICLE”。
在我的代碼中,我有它,以便它在從用戶輸入獲取所需信息后添加一個 Integer 和一個帶有 put 語句的 Vehicle,它適用於第一個輸入,但之后它剛剛被替換,我將如何循環put() 還是創建一個循環以將內容添加到地圖中?
(我還計划讓我的 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());
我希望添加許多輸入並得到類似的東西:
1 = Vehicle
2 = Vehicle
相反,我只是得到
1 = Vehicle
然后它將替換第一輛車然后發出
2 = Vehicle
我已經研究並意識到這是因為我只有 1 個 put 所以它只是替換了映射到那里的當前事物,我只是不確定如何循環它來解決這個問題。
每次調用 carInfo 方法時都會創建一個新的 HashMap,因此 HashMap 始終只有一個條目,您可以將 HashMap 作為類的局部變量來解決這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.