Java code: why 0.0 and -0.0 are considered to be two different keys in hashmap?


  • 0
    Z

    I use the slope of the line to be the key and number of points in the same line to be the value. But for the following test, when y of all the points are the same, hasmap got 0.0 and -0.0 as the keys, and they are considered to be different. I don't understand why java does this. In math, 0.0 and -0.0 have no difference. My code is following. Thanks.

    import java.util.*;
    class Point {
        int x;
        int y;
        Point() { x = 0; y = 0; }
        Point(int a, int b) { x = a; y = b; }
    }
    
    public class Solution {
        public int maxPoints(Point[] points) {
    		if(points.length <= 2)
    			return points.length;
    		
    		int n = points.length;
    		int globalMax = 2;
            for(int i = 0; i < n - 1; i++){
    			HashMap<Double, Integer> mp = new HashMap<Double, Integer>();
    			int dup = 0;
    			for(int j = i + 1; j < n; j++){
    				int dy = points[j].y - points[i].y;
    				int dx = points[j].x - points[i].x;
    				double k; 
    				if(dy == 0 && dx == 0){
    					dup++;
    					continue;
    				}
    				else if(dx == 0)
    					k = Double.MAX_VALUE;
    				else
    					k = ((double)dy) / ((double)dx);  // if I do not add 0.0, there will be error. It's strange to see that 0.0 and -0.0 can be two different keys in hashmap.
    					//k = ((double)dy) / ((double)dx) + 0.0;
    				
    				if(!mp.containsKey(k))
    					mp.put(k, 2);
    				else
    					mp.put(k, mp.get(k)+1);
    			}
    			int localMax = 1;
    			for(Map.Entry<Double, Integer> entry : mp.entrySet()){
    				double key = entry.getKey();
    				System.out.println(key); // print out the keys and found that 0.0 is different from -0.0;
    				if(mp.get(key) > localMax)
    					localMax = mp.get(key);
    			}
    			localMax += dup;
    			if(localMax > globalMax)
    				globalMax = localMax;
    		}
    		
    		return globalMax;
        }
    	
    	public static void main(String[] args){
    		Point p1 = new Point(2, 3);
    		Point p2 = new Point(5, 3);
    		Point p3 = new Point(-3, 3);
    		Point[] x = {p1, p2, p3};
    		
    		Solution slt = new Solution();
    		System.out.println("Print keys at first. Last is the final result");
    		System.out.println(slt.maxPoints(x));
    		
    	}
    }

  • 1
    Y

    0.0 and -0.0 have different binary representation (0x000000 and 0x00000004). Good hash function should make same hash value, for example in C++ std::hash<float>()( 0.0f ) is equal to std::hash<float>()( -0.0f ) .
    Not sure, why in Java it's different


  • 0
    Z

    Yep. Strange. Thanks for answering.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.