How to call a method from another class in Java

让人想犯罪 __ 提交于 2019-12-06 14:42:05

I see that you get Product object with ref "a" as parameter to your addProd method.

And you can get id by just using a.getID(). It should look as:

  public void addProd(Product a) {

      prod.put(a.getID(),a);
  }  

I didn't understand second part of your question.. I think you already have 3 values in your Product object and you put Product object to Map, So why do you require another way ?

Your class Product does not compile, because you have the name Item in your constructor. The constructor name must match the class name. So change that to Product. The same applies to Invoice vs ShoppingCart. Constructor and Class names must match.

As per your comment, you'd like to add four product values to a Map. The key being one of the values of the product itself. Try this:

Product p = new Product(name, id, info, quantity);
cart.addProd(p);

...

public void addProd(Product p) {
    prod.put(p.getId(), p);
}

Maps can only map a single value to a single key, so you must have some sort of container for the values you wish to collate into one value. This can be an object (Product) or you could use a collection (e.g. List). I strongly recommend the former.

For your question about putting 3 values in your map, I don't think there's a way for you to put 3 values into one key without creating a class. An alternative is to store a Map<String, List<String>> assuming your 3 values are type String, or, Map<String, Map<String, String>>.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!