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?