1

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?

narendra
  • 199
  • 3
  • 8

1 Answers1

1

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.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Right.But, on what basis containsKey will check if the specified key is present or not? As per my understanding,it will calculate the hashcode of object which we pass.here I am passing key as 2 for(ex.),then every time I call containsKey(2) I should get the same hashcode right?then why doesn't it work?please clarify. – narendra Dec 02 '18 at 16:07
  • It looks at the hashcode first to find the bucket an object should be in, but it still compares the objects found in that bucket using `equals` afterwards (because a hashcode can collide). And that `equals` fails between Long and Integer. – Thilo Dec 02 '18 at 23:50