[英]Iterating through an ArrayList in a HashMap
我有以下HashMap:
HashMap<Integer, ArrayList<Integer>> mat = new HashMap<Integer, ArrayList<Integer>>();
看起来像这样:
1: [2, 3]
2: [1, 4, 5]
3: [1, 6, 7]
我的问题是:
如何在HashMap的第i个条目中获取ArrayList的大小?
如何在给定键上访问ArrayList中的第i个元素?
如何在HashMap的第i个条目中获取ArrayList的大小?
我假设您的意思是键为i
的条目。 (由于HashMap
的元素没有排序,因此谈论HashMap
的第i个条目没有意义。)
ArrayList<Integer> tmp = mat.get(i);
if (tmp != null) {
System.out.println("The size is " + tmp.size());
}
如何在给定键上访问ArrayList中的第i个元素?
我假设您想要数组的常规(对于Java)基于零的索引
ArrayList<Integer> tmp = mat.get(key);
if (tmp != null && i >= 0 && i < tmp.size()) {
System.out.println("The element is " + tmp.get(i));
}
请注意,如果要避免出现异常,需要处理各种边缘情况 。 (我已经处理过了……)
如何在HashMap的第i个条目中获取ArrayList的大小?
如果i不是您的HashMap的key
,恐怕我们无法直接获取HashMap i-th entry
。
Hashmap可以包含空值,因此您需要在使用arraylist
的size()
和get(i)
之前进行null
检查。
1)如何获取HashMap的第i个条目中ArrayList的大小?
ArrayList<Integer> list = mat.get(i);
if(list != null) {
list.size(); //gives the size of the list
}
2)如何在给定键上访问ArrayList中的第i个元素?
ArrayList<Integer> list = mat.get(i);
if(list != null) {
list.get(i);//gives the i-th element from list
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.