How to correctly use HashMap?

前端 未结 6 1829
长情又很酷
长情又很酷 2021-01-04 07:28
HashMap savedStuff = new HashMap();
savedStuff.put(\"symbol\", this.symbol); //this is a string
savedStuff.put(\"index\", this.index); //this is an int
6条回答
  •  有刺的猬
    2021-01-04 07:52

    I'm not sure what you're trying to do, but since the example you provided uses hard-coded strings to index the data, it seems like you know what data you want to group together. If that's the case, then a Map is probably not a good choice. The better approach would be to make a class out of the commonly grouped data:

    public class SavedStuff {
      private int index;
      private String symbol;
    
      public SavedStuff(int index, String symbol) {
        this.index = index;
        this.symbol = symbol;
      }
    
      public int getIndex() {
        return index;
      }
    
      public String getSymbol() {
        return symbol;
      }
    }
    

    This allows your client code to do this:

    SavedStuff savedStuff = ...
    String symbol = savedStuff.getSymbol();
    

    Rather than this:

    Map savedStuff = ...
    String symbol = savedStuff.get("symbol");
    

    The former example is much less fragile because you're not indexing data with String constants. It also gives you a place to add behavior on top of your grouped data, which makes your code much more object oriented.

提交回复
热议问题