代码之家  ›  专栏  ›  技术社区  ›  Sheehan Alam

如何正确使用HashMap?

  •  12
  • Sheehan Alam  · 技术社区  · 15 年前
    HashMap savedStuff = new HashMap();
    savedStuff.put("symbol", this.symbol); //this is a string
    savedStuff.put("index", this.index); //this is an int
    

    HashMap is a raw type. References to generic type HashMap<K,V> should be parameterized  
    
    6 回复  |  直到 15 年前
        1
  •  4
  •   Javid Jamae    15 年前

    我不确定您要做什么,但是由于您提供的示例使用硬编码字符串来索引数据,因此您似乎知道要将哪些数据分组在一起。如果是这样的话,那么地图可能不是一个好的选择。更好的方法是从通常分组的数据中生成一个类:

    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;
      }
    }
    

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

    而不是这个:

    Map<String, Object> savedStuff = ...
    String symbol = savedStuff.get("symbol");
    

    前一个例子不那么脆弱,因为您没有使用字符串常量索引数据。它还为您提供了一个在分组数据之上添加行为的位置,这使您的代码更加面向对象。

        2
  •  7
  •   Matthew Flaschen    15 年前
    HashMap<String, Object> savedStuff = new HashMap<String, Object>();
    

    当然,在提取元素时仍然需要小心使用正确的类型。

        3
  •  7
  •   fastcodejava    15 年前

    你需要使用 generics

    Map<String, Object> savedStuff = new HashMap<String, Object>();
    
        4
  •  4
  •   Alex Martelli    15 年前

    使用 HashMap<String, Object> 那些 当你取回它们的时候做一些有用的事情(你怎么知道要把它们转换成什么类型 钥匙 .

        5
  •  2
  •   Sean Patrick Floyd    15 年前

    这里有一种不同的方法:

    包含映射并提供其不同视图的帮助器类:

    public class ValueStore {
    
    
        /**
         * Inner map to store values.
         */
        private final Map<String,Object> inner = new HashMap<String,Object>();
    
        /**
         * Returns true if the Value store contains a numeric value for this key.
         */
        public boolean containsIntValue(final String key){
            return this.inner.get(key) instanceof Integer;
        }
    
    
        /**
         * Returns true if the Value store contains a String value for this key.
         */
        public boolean containsStringValue(final String key){
            return this.inner.get(key) instanceof String;
        }
    
        /**
         * Returns the numeric value associated with this key.
         * @return -1 if no such value exists
         */
        public int getAsInt(final String key){
            final Object retrieved = this.inner.get(key);
            return retrieved instanceof Integer ? ((Integer) retrieved).intValue() : -1;
        }
    
    
        /**
         * Returns the String value associated with this key.
         * @return null if no such value exists
         */
        public String getAsString(final String key){
            final Object retrieved = this.inner.get(key);
            return retrieved instanceof String ? (String) retrieved : null;
        }
    
        /**
         * Store a string value.
         */
        public void putAsInt(final String key, final int value){
            this.inner.put(key, Integer.valueOf(value));
        }
    
    
        /**
         * Store an int value.
         */
        public void putAsString(final String key, final String value){
            this.inner.put(key, value);
        }
    
        /**
         * Main method for testing.
         */
        public static void main(final String[] args) {
            final ValueStore store = new ValueStore();
            final String intKey = "int1";
            final String stringKey = "string1";
            final int intValue = 123;
            final String stringValue = "str";
    
            store.putAsInt(intKey, intValue);
            store.putAsString(stringKey, stringValue);
    
            assertTrue(store.containsIntValue(intKey));
            assertTrue(store.containsStringValue(stringKey));
            assertFalse(store.containsIntValue(stringKey));
            assertFalse(store.containsStringValue(intKey));
            assertEquals(123, store.getAsInt(intKey));
            assertEquals(stringValue, store.getAsString(stringKey));
            assertNull(store.getAsString(intKey));
            assertEquals(-1, store.getAsInt(stringKey));
        }
    
    }
    

    在检索int值之前,需要检查 store.containsIntValue(intKey) 在检索字符串值之前 store.containsStringValue(stringKey) . 这样就永远不会检索到错误类型的值。

    (当然也可以扩展到支持其他类型)

        6
  •  2
  •   Anuj Dhiman    5 年前

    这是使用hashmap的简单代码。在那里,我将使用键作为整数,值作为字符串类型。当我们的功能作用于键和值对时,Map非常有用。下面是使用hashmap的简单示例。我希望它对大家都很有用。

    public class CreateHashMap {
    
        public static void main(String[] args) {
    
        Map<Integer,String> map = new HashMap<Integer,String>();
    
        /*
         * Associates the specified value with the specified key in 
           this map (optional operation). If the map previously 
           contained a mapping for the key, the old value is 
           replaced by the specified value
         */
            map.put(1,"ankush");
            map.put(2, "amit");
            map.put(3,"shivam");
            map.put(4,"ankit");
            map.put(5, "yogesh");
    
            //print hashmap
            System.out.println("HashMap = "+map);
    
    
        }
    
    }
    

    create and use of map