通过嵌套for循环初始化哈希映射

时间:2016-04-12 08:19:02

标签: java for-loop collections hashmap nested-loops

我想要一个哈希映射来存储键和值的整数。通过使用嵌套的for循环我认为它应该工作。我似乎不完全理解嵌套循环中的程序流程。在我的代码下面:

import java.util.HashMap;

public class Main {

public static void main(String[] args) {

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

    //initializing running variables here to reuse in "display hashmap" loop
    int key = 48;
    int values = 65;

    //set keys and values to hashmap via nested for-loop 
    for (key = 48; key < 74; key++) {
        for (values = 65; values < 91; values++) {
            hMap.put(key, values);
        }
    }

    //display hashmap via nested for-loop
    for (key = 48; key < 74; key++) {
        System.out.println("Key: " + key + ", Value: " + hMap.get(key));
    }
  }
}

这是当前控制台输出:

Key: 48, Value: 90
Key: 49, Value: 90
Key: 50, Value: 90
Key: 51, Value: 90
Key: 52, Value: 90
Key: 53, Value: 90
...

这是我想要的控制台输出:

Key: 48, Value: 65
Key: 49, Value: 66
Key: 50, Value: 67
Key: 51, Value: 68
Key: 52, Value: 69
Key: 53, Value: 70
...

我现在知道内部for循环运行直到满足结束条件,因此覆盖了变量value。但是如何实现如上所示的预期控制台输出?

提前多多谢谢。我更喜欢初学者友好的回复:)

2 个答案:

答案 0 :(得分:1)

您不需要嵌套循环。您正尝试key value在48和73之间的所有组合以及int value = 65; for (int key = 48; key < 74; key++) { hMap.put (key, value++); } 在65和90之间的映射,但只保留每个键的最后一个值,因为地图不允许重复键。

单个循环可以满足您的需求:

value++

value置于Map中会将value的当前值放入Map中,并为下一次迭代增加int value = 65; for (int key = 48; key < 74; key++) { hMap.put (key, value); value++ } 变量。它相当于:

matplotlib

答案 1 :(得分:0)

问题出在循环中。对于每个键,您将重复所有值的放置。

像这样添加和输出:

In [197]: ticks
Out[197]: ['', u'0', u'2', u'4', u'6', u'8', u'10', '']

你会看到你的错误:

for (key = 48; key < 74; key++) {
    for (values = 65; values < 91; values++) {
        hMap.put(key, values);
        System.out.println("put Key: " + key + ", Value: " + values);
    }
}

每个键的地图中的最后一个值始终为put Key: 48, Value: 65 put Key: 48, Value: 66 put Key: 48, Value: 67 put Key: 48, Value: 68 put Key: 48, Value: 69 put Key: 48, Value: 70 put Key: 48, Value: 71 put Key: 48, Value: 72 put Key: 48, Value: 73 put Key: 48, Value: 74 put Key: 48, Value: 75 put Key: 48, Value: 76 put Key: 48, Value: 77 put Key: 48, Value: 78 put Key: 48, Value: 79 put Key: 48, Value: 80 put Key: 48, Value: 81 put Key: 48, Value: 82 put Key: 48, Value: 83 put Key: 48, Value: 84 put Key: 48, Value: 85 put Key: 48, Value: 86 put Key: 48, Value: 87 put Key: 48, Value: 88 put Key: 48, Value: 89 put Key: 48, Value: 90 put Key: 49, Value: 65 put Key: 49, Value: 66 put Key: 49, Value: 67 put Key: 49, Value: 68 put Key: 49, Value: 69 put Key: 49, Value: 70 ...

试试这个:

90