Java - LinkedHashMap(有序 map)获取第一个元素和最后一个元素
发布日期:2021-06-30 23:28:58
浏览次数:2
分类:技术文章
本文共 2481 字,大约阅读时间需要 8 分钟。
获取LinkedHashMap中的头部元素(最早添加的元素):时间复杂度O(1)
publicEntry getHead(LinkedHashMap map) { return map.entrySet().iterator().next();}
获取LinkedHashMap中的末尾元素(最近添加的元素):时间复杂度O(n)
publicEntry getTail(LinkedHashMap map) { Iterator > iterator = map.entrySet().iterator(); Entry tail = null; while (iterator.hasNext()) { tail = iterator.next(); } return tail;}
通过反射获取LinkedHashMap中的末尾元素:时间复杂度O(1),访问tail属性
publicEntry getTailByReflection(LinkedHashMap map) throws NoSuchFieldException, IllegalAccessException { Field tail = map.getClass().getDeclaredField("tail"); tail.setAccessible(true); return (Entry ) tail.get(map);}
测试代码
import static org.junit.Assert.assertEquals;import java.lang.reflect.Field;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map.Entry;import org.junit.Before;import org.junit.Test;public class TestLinkedHashMap { private LinkedHashMapmap = new LinkedHashMap<>(); private String letters[] = { "a", "b", "c", "d", "e" }; @Before public void init() { for (int i = 0; i < letters.length; i++) { map.put(letters[i], i + 1); } } @Test public void testGetHead() { assertEquals(getHead(map).getKey(), "a"); assertEquals(getHead(map).getValue(), Integer.valueOf(1)); } @Test public void testGetTail() { assertEquals(getTail(map).getKey(), "e"); assertEquals(getTail(map).getValue(), Integer.valueOf(5)); } @Test public void testGetTailByReflection() throws NoSuchFieldException, IllegalAccessException { assertEquals(getTailByReflection(map).getKey(), "e"); assertEquals(getTailByReflection(map).getValue(), Integer.valueOf(5)); } public Entry getHead(LinkedHashMap map) { return map.entrySet().iterator().next(); } public Entry getTail(LinkedHashMap map) { Iterator > iterator = map.entrySet().iterator(); Entry tail = null; while (iterator.hasNext()) { tail = iterator.next(); } return tail; } @SuppressWarnings("unchecked") public Entry getTailByReflection(LinkedHashMap map) throws NoSuchFieldException, IllegalAccessException { Field tail = map.getClass().getDeclaredField("tail"); tail.setAccessible(true); return (Entry ) tail.get(map); }}
转载地址:https://lux-sun.blog.csdn.net/article/details/107628507 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月20日 12时49分32秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
一本书搞定Python入门到实践
2019-05-01
2017半年文章合集(建议收藏)
2019-05-01
简析 __init__、__new__、__call__ 方法
2019-05-01
程序员如何优雅地写公众号
2019-05-01
@classmethod与@staticmethod的区别
2019-05-01
只有1%的程序员搞懂过浮点数陷阱
2019-05-01
Google 为什么把几十亿行代码放在一个库
2019-05-01
Erlang 之父 Joe Armstrong 去世
2019-05-01
来不及了,世界读书日,送10本书
2019-05-01
速来,上期中奖名单
2019-05-01
一名 Google 工程师的大数据处理经验
2019-05-01
30分钟学会pyecharts数据可视化
2019-05-01
从一个骗子身上学到的
2019-05-01
关于Python爬虫,这里有一条高效的学习路径
2019-05-01
Python学习指南,看这篇清晰多了!
2019-05-01
Oracle裁员,3点建议
2019-05-01
「忙」只是借口
2019-05-01
如果只有1小时学Python,看这篇就够了
2019-05-01
命名难,难于上青天
2019-05-01
记一件小事
2019-05-01