Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Objects in Java Map not accessing properties

I made some objects and I put them into a Map<Integer, Object> pairs.
When I iterate through the map, I can’t access any of the properties of the objects, they show up as null but the object is present and can be confirmed through

inventory2.containsValue(objName);

public class Obj {

    public String name;
    public int quantity;

    public Obj(String name, int quantity) {
        name = this.name;
        quantity = this.quantity;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    @Override
    public String toString() {
        return "obj [name=" + name + ", quantity="
                + quantity + "]";
    }
public static void mapReview() {

    Map<Integer, Obj> inventory2 = new HashMap<>();
    Obj greenHerb = new Obj("Green Herb",2);
    Obj redHerb = new Obj("Red Herb", 4);

    for(int k = 0; k < inventory2.size(); k++) {
        System.out.println("Key is: " + k + " and name is: " + inventory2.get(k).getName() + " and quantity is: " + inventory2.get(k).getQuantity());
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your constructor assignments are wrong, they should be the other way around.

Instead of:

name = this.name;
quantity = this.quantity;

It should be:

this.name = name;
this.quantity = quantity;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading