简体   繁体   中英

Grab a specific HashMap entity and grab details

Here are my classes:

HouseDetails:

private String forename;
private String surname;
private double houseName;
private int numberofHouses;


public CreditCardDetails(String forename, String surname, double houseName, int numberofHouses) {
    this.forename = forename;
    this.surname = surname;
    this.houseName = houseName;
    this.numberofHouses = numberofHouses;
}

HousePurchase:

 HashMap <String, HouseDetails> houses = new HashMap<String, HouseDetails>();

This is just an example. I'm trying to see if the houseNumber first exists, and then check if the houseNumber is associated with the numberOfHouses.

This is what i have tried so far:

public void checkIfHouseMatches(String number ,int numberofHouses){
    for (HouseDetails det : houses.values()) 
        if (houses.containsKey(number) && det.getNumberofHouses() == numberOfHouses) {
            System.out.println("True");
        }
        else {
        }

However, this returns true if the numberofHouses matches any of the entities within the HashMap, instead of the specific house number that i have entered.

How do i fix this?

your check is wrong.

What you are doing right now will check if the map contains the number and if any HouseDetails has numberOfHouses which you passed, it will return true

Suppose you have 3 house details

HouseDetail1 (number = 1, noOfHouses = 5)
HouseDetail2 (number = 2, noOfHouses = 6)
HouseDetail3 (number = 3, noOfHouses = 5)

and you searched for number 1 and noOfHouses = 6 First iteration will ll be false, because houses.containsKey(number) is true but det.getNumberofHouses() == numberOfHouses is false

Second iteration both will be true -- but this is wrong. Change it to something like :

if(houses.containsKey(number)){
     if(houses.get(number).getNumberofHouses() == numberOfHouses){
         System.out.println("True");
     }else{
    }
 }

If you want to access the details from a specific entry in the HashMap, you use the get(Object key) method. In your case the checkIfHouseMatches can be implemented as:

return houses.containsKey(number) ? houses.get(number).getNumberofHouses() == numberofHouses : false;

No need to iterate over the values of the map.

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