Java 如何正确使用HashMap?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3640648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:03:24  来源:igfitidea点击:

How to correctly use HashMap?

javadata-structuresmaphashmapkey-value

提问by Sheehan Alam

HashMap savedStuff = new HashMap();
savedStuff.put("symbol", this.symbol); //this is a string
savedStuff.put("index", this.index); //this is an int

gives me the warning:

给我警告:

HashMap is a raw type. References to generic type HashMap<K,V> should be parameterized  

采纳答案by Javid Jamae

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:

我不确定您要做什么,但由于您提供的示例使用硬编码字符串来索引数据,因此您似乎知道要将哪些数据组合在一起。如果是这种情况,那么 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;
  }
}

This allows your client code to do this:

这允许您的客户端代码执行此操作:

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

Rather than this:

而不是这样:

Map<String, Object> 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.

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

回答by Matthew Flaschen

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

Of course, you will still have to be careful to use the right type when extracting elements.

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

回答by Alex Martelli

Using HashMap<String, Object>is probably the best you can do if you insist on having heterogeneous values in the same map -- you'll need to cast thoseto do anything useful when you retrieve them (and how are you going to know what type to cast them to...?), but at least you'll be typesafe with respect to the keys.

HashMap<String, Object>如果您坚持在同一个映射中具有异构值,则使用可能是您能做的最好的事情——当您检索它们时,您需要强制转换它们以做任何有用的事情(以及您将如何知道将它们转换为什么类型)...?),但至少你会在key方面是类型安全的。

回答by fastcodejava

You need to use genericsas shown below :

您需要使用泛型,如下所示:

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

回答by Sean Patrick Floyd

Here is a different Approach:

这是一种不同的方法:

A Helper class that contains a map and provides different views of it:

包含地图并提供其不同视图的 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));
    }

}

Before you would retrieve an int value, you would check the value of store.containsIntValue(intKey)and before you retrieve a String value, you would check store.containsStringValue(stringKey). That way you would never retrieve values of the wrong type.

在检索 int 值之前,您将检查 的值,store.containsIntValue(intKey)在检索 String 值之前,您将检查store.containsStringValue(stringKey). 这样你就永远不会检索错误类型的值。

(Can of course be extended to support other types as well)

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

回答by Anuj Dhiman

This is simple code for use of hashmap. There i will use key as integer and value as string type. Map is very useful when our functionality works on key and values pairs. Below is a simple example of use hashmap. I hope it is very useful for all.

这是使用 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);


    }

}

Reference : create and use of map

参考:map的创建和使用