Home > Software design >  How to make an object store itself in a hashmap
How to make an object store itself in a hashmap

Time:12-20

So I have 4 classes, Testest which has a main method, Phone which extends Product, Product and ProductDB which has a hashmap. When I make a new phone I want the phone to be stored in the database automatically.

public class Product {

protected String productID;
protected String name;
private String description;
private double price;

public Product(){
    Product db = new ProductDB();
    productID = this.toString();
    db.add(productID, this);
}
(Getter and setter methods here...)
}


public class Phone extends Product {

private String make;
private String model;
private int storage;
public Phone(String make, String model, int storage){
    this.make = make;
    this.model = model;
    this.storage = storage;
}
(Getter and setter methods here...)
}


import java.util.HashMap;
public class ProductDB {
    private HashMap<String,Product> products = new HashMap<String, Product>();
    public void add(String productID, Product product){
        products.put(productID, product);
    }
    public void remove(String productID){
        products.remove(productID);
    }
    public Product find(String productID){
        return products.get(productID);
    }
    public Object showAll(){
        return products.values().toArray();
    }

}

public class Testest{
 public static void main(String[] args){
     ProductDB db = new ProductDB();
     Phone phone1 = new Phone("Huwawei P30", "HP30", 50000);
     Phone phone2 = new Phone("Huwawei P30 Pro", "HP30PRO", 70000);
     Phone phone3 = new Phone("Samsung Galaxy SX", "SGSX", 65000);
     System.out.println(db.find(phone1.productID));
     System.out.println(phone1.productID);
 }
}

I want this to return the object when I look for that specific id, but the problem is that the HashMap is empty for some reason

Edit I made productID private. Still nothing

CodePudding user response:

It seems you want your database to include all created phones, in this case instead of creating a database each time which will be useless and also because your database is accessed from several places it will be more consistent to make your database fields and methods static and just access it from where you want:

public class ProductDB {
    final private static HashMap<String,Product> products = new HashMap<String, Product>();
    public static void add(String productID, Product product){
        products.put(productID, product);
    }
    public static void remove(String productID){
        products.remove(productID);
    }
    public static Product find(String productID){
        return products.get(productID);
    }
    public static Object showAll(){
        return products.values().toArray();
    }

}

And then in Product constructor just write:

    public Product{
        productID = this.toString();
        ProductDB.add(productID, this);
    }
  • Related