Printing HashMap In Java

后端 未结 15 1731
半阙折子戏
半阙折子戏 2020-11-28 19:32

I have a HashMap:

private HashMap example = new HashMap();

Now I would lik

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 19:41

    A simple print statement with the variable name which contains the reference of the Hash Map would do :

    HashMap HM = new HashMap<>(); //empty
    System.out.println(HM); //prints key value pairs enclosed in {}
    

    This works because the toString()method is already over-ridden in the AbstractMap class which is extended by the HashMap Class More information from the documentation

    Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

提交回复
热议问题