Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

java - How to add element at specific index/position in LinkedHashMap?

I have an ordered LinkedHashMap and i want to add element at specific index , say at first place or last place in the map. How can i add element in LinkedHashMap at an specific position?

Even if I could add an element to FIRST or LAST position in LinkedHashMap would help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do this element adding to 1. or last place:

Adding to last place ? You just need to remove the previous entry from the map like this:

map.remove(key);
map.put(key,value);

Adding to first place ? It's a bit more complicated, you need to clone the map, clear it, put the 1. value to it, and put the new map to it, like this:

I'm using maps with String keys and Group (my custom class) values:

LinkedHashMap<String, Group> newMap=(LinkedHashMap<String, Group>) map.clone();
map.clear();
map.put(key, value);
map.putAll(newMap);

As you see, with these methods you can add unlimited amount of things to the begin and to the end of the map.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...