Question Description:
Suppose you are traversing a series of 3D points in an AR game, and the goal of the game is to not visit the same location (same x, y, z coordinate) twice. How would you implement a Point class that can keep track of the coordinates you've been to?
Hints:
public class HashSetPoints {
public static class Point{
int x;
int y;
int z;
public Point(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
}
public static void driver(){
Point p1 = new Point(1,1,1);
Point p2 = new Point(2,2,2);
Point p3 = new Point(1,1,1);
HashSet<Point> visited = new HashSet<Point>();
visited.add(p1);
visited.add(p2);
visited.add(p3);
System.out.println("visited" + visited.size()); // expect 2 since p1 and p3 and the same points
}
}Where have you first heard of this question:
Interview question
Solution:
You need to implement both equals and hashCode method of the Point class. For java object, if two objects are equal to each other, they must have the same hashCode. If you want to dive deep, look at how a HashSet's add is implemented, some where down the stack there is a point where equals() and hashCode() are being used to determine whether to add the new object to the HashSet. The default hashcode is implemented by Java System identityHashCode (implemented the JVM), using the address of the object and converting it into an int. There are many ways to implement this solution.
Here is a sample solution:
private int x;
private int y;
private int z;
public Point(int x, int y, int z){
super();
this.x = x;
this.y = y;
this.z = z;
}
@Override
public boolean equals(Object obj ){
if (!(obj instanceof Point)){
return false;
}
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Point p = (Point) obj;
return ( p.x == this.x) && (p.y == this.y) &&(p.z == this.z);
};
public int hashCode(){
return this.x + this.y + this.z;
}
}