当需要替换Map中的某个key的value时,不同的Map会有不同的现象。
当使用HashMap的时候,会打乱原来的顺序,即使HashMap本来就是无序的,但还是有的场景需要知道位置或者是不影响原来的位置,所以真有这种需要替换某个value的场景,还需要保持原来的顺序的,那就需要使用LinkedHashMap。以下就是实际测试的代码日志,可以参考:
public class TestActivity extends AppCompatActivity {
Map<String, String> map = new HashMap();
Map<String, String> lmap = new LinkedHashMap<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
map.put("111", "111");
map.put("555", "222");
map.put("333", "333");
lmap.put("111", "111");
lmap.put("555", "222");
lmap.put("333", "333");
findViewById(R.id.btnMap).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
map.put("555", "444");
lmap.put("555", "444");
for (Map.Entry<String, String> entry : map.entrySet()){
Log.i("map--->>>","Key::" + entry.getKey() + "--Value::" + entry.getValue());
}
for (Map.Entry<String, String> entry : lmap.entrySet()){
Log.i("lmap--->>>","Key::" + entry.getKey() + "--Value::" + entry.getValue());
}
}
});
}
}
日志如下:
I/map--->>>: Key::111--Value::111
I/map--->>>: Key::333--Value::333
I/map--->>>: Key::555--Value::444
I/lmap--->>>: Key::111--Value::111
I/lmap--->>>: Key::555--Value::444
I/lmap--->>>: Key::333--Value::333