java - hash value for a line object -


here reference implementation of line object, confusion line 40 line 43, question is, if 2 lines different, or results of slope/intercept happens same, have issues (e.g. treat different lines same because of same hash values)? since think same hash value means same line.

if current implementation hash value have issue mentioned, appreciate if provide insights implementation hash value in case.

1 public static line findbestline(graphpoint[] points) { 2 line bestline = null; 3 hashmap<line, integer> line_count = new hashmap<line, integer>(); 4 (int = 0; < points.length; i++) { 5 (int j = + 1; j < points.length; j++) { 6 line line = new line(points[i], points[j]); 7 if (!line_count.containskey(line)) { 8 line_count.put(line, 0); 9 } 10 line_count.put(line, line_count.get(line) + 1); 11 if (bestline == null || 12 line_count.get(line) > line_count.get(bestline)) { 13 bestline = line; 14 } 15 } 16 } 17 return bestline; 18 } 19 20 public class line { 21 private static double epsilon = .0001; 22 public double slope; 23 public double intercept; 24 private boolean infinite_slope = false; 25 public line(graphpoint p, graphpoint q) { 26 if (math.abs(p.x - q.x) > epsilon) { // if x’s different 27 slope = (p.y - q.y) / (p.x - q.x); // compute slope 28 intercept = p.y - slope * p.x; // y intercept y=mx+b 29 } else { 30 infinite_slope = true; 31 intercept = p.x; // x-intercept, since slope infinite 32 } 33 } 34 35 public boolean isequal(double a, double b) { 36 return (math.abs(a - b) < epsilon); 37 } 38 39 @override 40 public int hashcode() { 41 int sl = (int)(slope * 1000); 42 int in = (int)(intercept * 1000); 43 return sl | in; 44 } 45 46 @override 47 public boolean equals(object o) { 48 line l = (line) o; 49 if (isequal(l.slope, slope) && isequal(l.intercept, intercept) 50 && (infinite_slope == l.infinite_slope)) { 51 return true; 52 } 53 return false; 54 } 55 } 

since think same hash value means same line.

no, doesn't. common misconception. if 2 objects have same hash code, may equal - don't have be. should never treat equal hash codes proof 2 objects equal.

the hash code used here poor in various ways, @ least valid.

as extreme example, it's valid (but unhelpful) write:

public override int hashcode() {     return 5; } 

that guarantees objects equal have same hash code, that's required correctness. beyond correctness, ensuring non-equal objects have different hash codes matter of making efficient use type in hash-based lookup.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -