我正在使用 hasmap 和 LinkedHasmap 一段时间,但现在在这种情况下表现得很奇怪,我正在向 hasmap 添加一个键和一个来自 2 个具有相同大小的数组的值,在这种情况下大小为 4,但是 hasmap 在调试中将第一个键设置为 null 我看到它会覆盖相同位置的第二个键有第一个,它从来没有相同的键而且从来没有相同的所以我无法理解发生了什么。
声明的 hasmap 有一个字段。
private HashMap<String, String> courses = new HasMap<String, String>();
在这个方法中我想填充 hasMap:
private void coursesInit(int coursesListSize) {
for (int j = 0; j < coursesListSize; j++) {
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout inserPoint = (LinearLayout) findViewById(R.id.linear_layout_inside_left);
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
View view = inflater.inflate(R.layout.courses_button_left_drawer,
null);
Button btnTag = (Button) view.findViewById(R.id.course_id);
btnTag.setLayoutParams(new LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
if (coursesIdList.isEmpty()) {
btnTag.setText("Your Course " + (j + 1));
btnTag.setId(j);
} else {
btnTag.setText(coursesNamesList.get(j));
btnTag.setId(Integer.parseInt(coursesIdList.get(j)));
// Populate LinkedHasMap in the correct order where Key=
// course_id && Value= course_fullname
courses.put(coursesIdList.get(j), coursesNamesList.get(j));
}
if (j != 0) {
btnTag.setBackgroundResource(R.drawable.border_inside);
}
row.addView(view);
inserPoint.addView(row, 3);
}
}
我也曾尝试过只使用 Map 和 LinkedHasMap 并在一个方法中只使用 for 循环数组,但结果相同。
调试截图:
类(class)HasMap: Courses Hasmap
数组: Arrays
最佳答案
如果您的问题是 HashMap
实例的 table[0]
元素在调试器中为 null
,那么这不是只要 HashMap
按照文档中的解释(确实如此)工作,就会出现问题。内部实现细节对你来说应该无关紧要(它是一个供你使用的黑盒子)。如果要检索 map 的键,请使用 HashMap#entrySet
。
请参阅以下 HashMap 中的单个插入示例和生成的 HashMap#table
字段:
final Map<String, String> map = new HashMap<String, String>();
map.put("One", "1");
如您所见,元素插入到 table[12]
。
同时记住HashMap
allows null as key ,因此如果您将 key 设置为空,则这是一个有效 key 。
关于java - HashMap 第一个键为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18538529/