7 Replies Latest reply: Nov 6, 2009 11:00 AM by 807580 RSS

    Hash maps

    807580
      Hi everyone,

      I would like to create a map with three different values in a map, which will be the name of an item (String), its price and the quantity (integers).

      But according to the java API you can only create an hash map with two values: the key, and the value.

      Do I have to create two different hash map?

      Thanking you,
      Henri
        • 1. Re: Hash maps
          796262
          Henri90 wrote:
          Hi everyone,

          I would like to create a map with three different values in a map, which will be the name of an item (String), its price and the quantity (integers).

          But according to the java API you can only create an hash map with two values: the key, and the value.

          Do I have to create two different hash map?

          Thanking you,
          Henri
          What you could do is create a single Object that contains an Item's price and quantity (probably even its name as well). Then map the String name to the corresponding Object (gee, I might even call it Item) and get to its values from there.
          • 2. Re: Hash maps
            807580
            By creating one object do you mean to do it like that :
            public void setItem(String name, int price, int quantity) {
            //omited code;
            }
            and then use the set item as the value in the hash map ?
            • 3. Re: Hash maps
              807580
              Just while you are here, I wanted to thank you for all your help for the past three month, I had a distinction for my store program ( I am a first year uni student and I started to learn java four month ago), thank you kevinaworkman.

              Now I am just trying to re-do it but with hash map instead of arrayList, just to learn hashmap.
              • 4. Re: Hash maps
                796262
                Henri90 wrote:
                By creating one object do you mean to do it like that :
                public void setItem(String name, int price, int quantity) {
                //omited code;
                }
                and then use the set item as the value in the hash map ?
                Uhh it depends on the omitted code, I suppose. What I mean is this:
                public class Item{
                   String name;
                   double price;
                   int quantity;
                   //constructor
                   public Item(String name, double price, int quantity){
                      this.name = name;
                      this.price = price;
                      this.quantity = quantity;
                   }
                   //getters and setters
                }
                
                public class TestItem{
                   public static void main(String [] args){
                      Item item = new Item("Cats", 29.99, 42);
                      HashMap itemMap = new HashMap();
                      itemMap.put("Cats", item);
                      //could be:
                      //itemMap.put(item.getName(), item);
                
                      //later:
                      Item cats = itemMap.get("Cats");
                      System.out.println("We have " + cats.getQuantity() + " " + cats.getName() + " for " + cats.getPrice());
                   }
                }
                • 5. Re: Hash maps
                  800581
                  Henri90 wrote:
                  I would like to create a map with three different values in a map, which will be the name of an item (String), its price and the quantity (integers).

                  But according to the java API you can only create an hash map with two values: the key, and the value.

                  Do I have to create two different hash map?
                  Create your own object that contains all of the required parameters (name, price, quantity and anything else you want). Then you will put that Item into the map as the value and use a unique identifier (the name?) as the key to add it to the map. If you do decide to use the name of the item as the key it's important to understand that each item will have to have a unique name. If you can't guarantee that you could use another value like product ID.

                  Here is some sample code:

                  The item that contains the name, price and quantity.
                  package tester;
                  
                  public class Item {
                       private String name;
                       private double price;
                       private int quantity;
                       
                       /**
                        * Create a new item with the given name, price and quantity
                        * @param name
                        * @param price
                        * @param quantity
                        */
                       public Item(String name, double price, int quantity) {
                            this.name = name;
                            this.price = price;
                            this.quantity = quantity;
                       }
                       
                       /**
                        * Get the name of this Item
                        * @return
                        */
                       public String getName() {
                            return name;
                       }
                       
                       /**
                        * Get the price of this item
                        * @return
                        */
                       public double getPrice() {
                            return price;
                       }
                       
                       /**
                        * Get the quantity of these items in stock
                        * @return
                        */
                       public int getQuantity() {
                            return quantity;
                       }
                       
                       /**
                        * Set the price of this item
                        * @param newPrice
                        */
                       public void setPrice(double newPrice) {
                            this.price = newPrice;
                       }
                       
                       /**
                        * Set the number of these items in stock
                        * @param newQuantity
                        */
                       public void setQuantity(int newQuantity) {
                            this.quantity = newQuantity;
                       }
                  }
                  ...and the driver for the application (creates map, adds items to it and performs operations on the map.
                  package tester;
                  
                  import java.util.HashMap;
                  import java.util.Map;
                  
                  public class ItemTester {
                       private Map<String, Item> items = new HashMap<String, Item>();
                       
                       public static void main(String[] args) {
                            new ItemTester();
                       }
                       
                       private ItemTester() {
                            populateMap();
                  
                            // Now print the price of the porsche
                            if(items.containsKey("Porsche 911")) {
                                 Item porscheItem = items.get("Porsche 911");
                                 
                                 System.out.println("Item name: "+porscheItem.getName()+", price: "+
                                           porscheItem.getPrice()+", quantity: "+porscheItem.getQuantity());
                            }
                            
                            // Print the total value of all cars
                            showTotalValueOfAllCars();
                            
                            // Someone has bought a Volvo, decrease the number of them in stock
                            customerBoughtItem("Volvo S40");
                  
                            // Print out the total value of the cars again
                            showTotalValueOfAllCars();
                       }
                       
                       private void populateMap() {
                            // Create some new items
                            Item porscheItem = new Item("Porsche 911", 99999.00, 10);
                            Item ferrariItem = new Item("Ferrari 355", 85000.00, 3);
                            Item volvoItem = new Item("Volvo S40", 30000.00, 20);
                            
                            // Add the items to the map
                            items.put(porscheItem.getName(), porscheItem);
                            items.put(ferrariItem.getName(), ferrariItem);
                            items.put(volvoItem.getName(), volvoItem);
                       }
                       
                       private void showTotalValueOfAllCars() {
                            double totalValueOfCars = 0;
                            
                            for(Item oneCar : items.values()) {
                                 double valueOfThisCar = oneCar.getPrice() * oneCar.getQuantity();
                                 
                                 totalValueOfCars += valueOfThisCar;
                            }
                            
                            System.out.println("Total value of all stock: "+totalValueOfCars);
                       }
                       
                       private void customerBoughtItem(String itemName) {
                            // Get the item that has been bought
                            if(items.containsKey(itemName)) {
                                 Item boughtItem = items.get(itemName);
                                 
                                 int previousQuantity = boughtItem.getQuantity();
                                 
                                 // Decrease the quantity in stock
                                 boughtItem.setQuantity(previousQuantity - 1);
                            } else {
                                 System.out.println("Could not find item in map! Item name: "+itemName);
                            }
                       }
                  }
                  • 6. Re: Hash maps
                    796262
                    amp88 wrote:
                    Here is some sample code:
                    Yikes, and here I was afraid that my sample code was too much spoon feeding...
                    • 7. Re: Hash maps
                      807580
                      thanks for your help, now I know how to use hash map, I just have to practice and go through the lecture notes again. Thank you very much for those examples.