英文:
Java HashMap key map doesn't look right
问题
以下是要翻译的内容:
如果有人能够帮忙仔细检查一下我下面的代码有什么问题,我将不胜感激。
我尝试了很多次和不同的方式,但仍然得到了我从未预期过的结果。
下面是一个返回Map值的方法
我调用了一次,传入值为0,它运行得很好。
-->结果很好,第一个键=0,值正确,一切都正确。
我第二次调用时传入值为1
-->结果是错误的,第一个键=16,我预期它应该等于12
public Map<Integer, String[]> noteNumberNoteNameMap;
public Map<Integer, String[]> getNoteNumberNoteNameMap(int octave ) {
noteNumberNoteNameMap = new HashMap<>();
noteNumberNoteNameMap.put(12*octave+0, new String[] { "C" });
noteNumberNoteNameMap.put(12*octave+1, new String[] { "C#", "Db" });
noteNumberNoteNameMap.put(12*octave+2, new String[] { "D" });
noteNumberNoteNameMap.put(12*octave+3, new String[] { "D#", "Eb" });
noteNumberNoteNameMap.put(12*octave+4, new String[] { "E" });
noteNumberNoteNameMap.put(12*octave+5, new String[] { "F" });
noteNumberNoteNameMap.put(12*octave+6, new String[] { "F#", "Gb" });
noteNumberNoteNameMap.put(12*octave+7, new String[] { "G" });
noteNumberNoteNameMap.put(12*octave+8, new String[] { "G#", "Ab" });
noteNumberNoteNameMap.put(12*octave+9, new String[] { "A" });
noteNumberNoteNameMap.put(12*octave+10, new String[] { "A#", "Bb" });
noteNumberNoteNameMap.put(12*octave+11, new String[] { "B" });
return noteNumberNoteNameMap;
}
请提供建议。
提前谢谢您。
英文:
Could some one please double check to see what wrong with my code below that would be appreciated.
I tried many times and different ways, but still give me the result which I never expected.
Below is the method which return a Map values
I made 1 called, with pass-in value==0, it works just fine.
-->result works fine, the first key=0 and value correct and all correct.
I made 2nd called with pass-in value=1
-->result is WRONG, the first key==16 where I expected it should be = 12
public Map<Integer, String[]> noteNumberNoteNameMap;
public Map<Integer, String[]> getNoteNumberNoteNameMap(int octave ) {
noteNumberNoteNameMap = new HashMap<>();
noteNumberNoteNameMap.put(12*octave+0, new String[] { "C" });
noteNumberNoteNameMap.put(12*octave+1, new String[] { "C#", "Db" });
noteNumberNoteNameMap.put(12*octave+2, new String[] { "D" });
noteNumberNoteNameMap.put(12*octave+3, new String[] { "D#", "Eb" });
noteNumberNoteNameMap.put(12*octave+4, new String[] { "E" });
noteNumberNoteNameMap.put(12*octave+5, new String[] { "F" });
noteNumberNoteNameMap.put(12*octave+6, new String[] { "F#", "Gb" });
noteNumberNoteNameMap.put(12*octave+7, new String[] { "G" });
noteNumberNoteNameMap.put(12*octave+8, new String[] { "G#", "Ab" });
noteNumberNoteNameMap.put(12*octave+9, new String[] { "A" });
noteNumberNoteNameMap.put(12*octave+10, new String[] { "A#", "Bb" });
noteNumberNoteNameMap.put(12*octave+11, new String[] { "B" });
return noteNumberNoteNameMap;
}
Please advise.
Thank you in advance.
答案1
得分: 0
HashMap不遵循插入顺序。如果您希望顺序遵循插入顺序,请使用LinkedHashMap。
英文:
HashMap doesn't follow the insertion order. If you want the order to be followed as insertion order, use LinkedHashMap
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论