Reputation: 189
I have below code to check if sum of distinct pairs is equal to a number.
static int numberOfPairs(int[] a, long k) {
Integer
Map<Integer,Integer> map = new HashMap<>();
int count =0;
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++) {
if(a[i]+a[j] == k){
if((!map.containsKey(a[i])) && (!map.containsKey(k-a[i]))) {
map.put(a[i], a[j]);
count++;
}
}
}
}
return count;
}
containskey method does not work for above code bcoz k is of type long.But code works if I convert long to int.
static int numberOfPairs(int[] a, long k) {
Integer
Map<Integer,Integer> map = new HashMap<>();
int count =0;
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++) {
if(a[i]+a[j] == k){
int x=(int)k-a[i];
if((!map.containsKey(a[i])) && (!map.containsKey(x))) {
map.put(a[i], a[j]);
count++;
}
}
}
}
return count;
}
Que : why didn't it work with long type?how does the containsKey method work?
Upvotes: 0
Views: 51
Reputation: 262684
map.containsKey(k-a[i])
This is checking for the presence of a Long
in a Map<Integer, Integer>
. This will always be false, even if the numeric value happens to be the same.
Note that long
needs to be boxed to be used as the argument to containsKey(Object key)
, but it will be auto-boxed to Long
, not Integer
.
A static code checker like Findbugs may give you a warning about this. If generics had made their way earlier into Java, this would probably even be the compile-time error you'd want here.
map.containsKey((int)(k-a[i]))
Now you have an int
, which will be boxed automatically to an Integer
and it works.
Upvotes: 0