【问题标题】:How to correctly use HashMap?如何正确使用HashMap?
【发布时间】:2011-04-08 03:01:53
【问题描述】:
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  

【问题讨论】:

  • apache commons Multivalue map 可以解决你的问题!

标签: java data-structures map hashmap key-value


【解决方案1】:
HashMap<String, Object> savedStuff = new HashMap<String, Object>();

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

【讨论】:

    【解决方案2】:

    你需要使用generics,如下图:

    Map<String, Object> savedStuff = new HashMap<String, Object>();
    

    【讨论】:

      【解决方案3】:

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

      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");
      

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

      【讨论】:

        【解决方案4】:

        使用HashMap&lt;String, Object&gt; 可能是最好的办法,如果您坚持在同一个映射中具有异构值 - 您需要在检索它们时强制转换 那些 来做任何有用的事情(以及您如何知道将它们转换为...的类型?),但至少对于,您将是类型安全的。

        【讨论】:

          【解决方案5】:

          这是一种不同的方法:

          一个包含地图并提供不同视图的 Helper 类:

          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) 的值,在检索 String 值之前,您将检查 store.containsStringValue(stringKey)。这样您就永远不会检索到错误类型的值。

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

          【讨论】:

            【解决方案6】:

            这是使用 hashmap 的简单代码。在那里我将使用键作为整数和值作为字符串类型。当我们的功能适用于键值对时,映射非常有用。下面是一个使用 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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-05-03
              • 1970-01-01
              • 2016-11-16
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多