Reputation: 83
I have the following HashMap:
HashMap<Integer, ArrayList<Integer>> mat = new HashMap<Integer, ArrayList<Integer>>();
which looks like this:
1: [2, 3]
2: [1, 4, 5]
3: [1, 6, 7]
My questions are:
How do I get the size of the ArrayList in the i-th entry of my HashMap ?
How do I access the i-th element in my ArrayList on a given key?
Upvotes: 1
Views: 80
Reputation: 719679
How do I get the size of the ArrayList in the i-th entry of my HashMap ?
I assume that you mean the entry whose key is i
. (Since the elements of a HashMap
are not ordered, it is not meaningful to talk about the i-th entry of a HashMap
.)
ArrayList<Integer> tmp = mat.get(i);
if (tmp != null) {
System.out.println("The size is " + tmp.size());
}
How do I access the i-th element in my ArrayList on a given key?
I assume that you want normal (for Java) zero-based indexing of the array
ArrayList<Integer> tmp = mat.get(key);
if (tmp != null && i >= 0 && i < tmp.size()) {
System.out.println("The element is " + tmp.get(i));
}
Note that there are various edge-cases that need to be dealt with if you want to avoid exceptions. (I have dealt with them ...)
Upvotes: 3
Reputation: 22452
Hashmap can contain null values, so you need to do the null
check before using the size()
and get(i)
of the arraylist
.
1) How do I get the size of the ArrayList in the i-th entry of my HashMap ?
ArrayList<Integer> list = mat.get(i);
if(list != null) {
list.size(); //gives the size of the list
}
2) How do I access the i-th element in my ArrayList on a given key?
ArrayList<Integer> list = mat.get(i);
if(list != null) {
list.get(i);//gives the i-th element from list
}
Upvotes: 0
Reputation: 2329
How do I get the size of the ArrayList in the i-th entry of my HashMap ?
if the i is not a key
of your HashMap, I'm afraid that we cant get the i-th entry
of HashMap directly.
Upvotes: 1