Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a hashmap with 4 objects?

Tags:

java

hashmap

Can I have an hashMap with say ID as my key and info, name, quantity as my values?

ok, say I have a class (Products) already that sets my variables, getters and setters. In my Invoice class, which is where the hashMap would be. Would I put like:

private HashMap<String, Products> keys = new HashMap<String, Products>

I'm not quite sure how to access the HashMap though. Say I implement a class that allows me to add and remove invoices from the HashMap, I do not know what the values would be:

keys.put(??value of id??,??not sure what goes here??);
like image 381
Jack Avatar asked Sep 20 '10 03:09

Jack


3 Answers

Sure. Make another class that contains your info, name and quantity and put that as the value of your HashMap.

like image 176
Starkey Avatar answered Nov 07 '22 05:11

Starkey


No, but the best way is to wrap the information you want to keep in the map in a class:

public class Info {
  private String info;
  private String name;
  private int quantity;

  ...

  public Info(String info, String name, int quantity) {
     ...
  }
}

Then do this to put something in the map:

Info info = new Info("info", "name", 2);
Map map = new HashMap<Integer, Info>();
map.put(22, info);

And do this to get something out:

Info info = map.get(22)
like image 34
Javid Jamae Avatar answered Nov 07 '22 07:11

Javid Jamae


How about HashMap<Integer, ArrayList<String>> ?

UPDATE: Please try to avoid this, this is a better approach.

like image 21
zengr Avatar answered Nov 07 '22 07:11

zengr