有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么要得到这个Hashmap输出?

import java.util.HashMap;

public class Map {

   public static void main(String[] args) {
       // TODO Auto-generated method stub

       int arr[] = {10, 3, 34, 3, 10};

       HashMap<Integer, Integer> hmap=new HashMap<Integer, Integer>();

       for (int i = 0; i < arr.length; i++) {
           System.out.println(hmap.put(arr[i], 1));
       }
   }
}

我得到的输出如下:

null
null
null
1
1

我没有得到为什么我得到的输出是三倍null和两倍一


共 (2) 个答案

  1. # 1 楼答案

    I am not getting why am i getting the output as "three times null and two times one".

    要理解这种行为背后的原因,需要阅读put方法的java规范

    put(K key, V value)

    returns the previous value associated with key, or null if there was no mapping for key.

    你想要的是:

    int arr[] = {10,3,34,3,10};
    
    HashMap<Integer,Integer> hmap = new HashMap<Integer,Integer>();
    for (int i = 0; i < arr.length; i++) {
         hmap.put(arr[i],1);
    }
    
    hmap.forEach((k, v) -> System.out.println("key = " + k + " value = " + v));
    

    输出:

    key = 34 value = 1
    key = 3 value = 1
    key = 10 value = 1
    

    如果您想知道为什么不打印arr数组中的所有键,那么这背后的原因很简单,因为:

    put(K key, V value) associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

    简单地说,HashMap键是唯一的,如果要添加任何重复的键,那么它将被覆盖

  2. # 2 楼答案

    Hashmapput函数在Hashmap中插入值,如果键已经存在,它将用新值替换键的旧值,并返回与键关联的前一个值,如果键没有映射,则返回null。当您插入前三个值,即10,3,34,因为它们在Hashmap中不存在,所以null会被返回,但是当您再次插入3时,这个键已经存在,所以put会替换旧值,并返回同一个键的旧值,即1,l,所以它会打印1。10人的情况也差不多