mirror of
https://gitlab.com/harald.mueller/aktuelle.kurse.git
synced 2024-11-24 18:51:56 +01:00
85 lines
2.4 KiB
Java
85 lines
2.4 KiB
Java
|
package m411;
|
||
|
|
||
|
import java.util.HashMap;
|
||
|
|
||
|
/**
|
||
|
* @author pius portmann, 07.01.2020
|
||
|
*/
|
||
|
public class Point3D {
|
||
|
|
||
|
private int x, y, z; // the coordinates
|
||
|
|
||
|
public Point3D() {
|
||
|
x = 0; y = 0; z = 0;
|
||
|
}
|
||
|
public Point3D(int x, int y, int z) {
|
||
|
this.x = x;
|
||
|
this.y = y;
|
||
|
this.z = z;
|
||
|
}
|
||
|
|
||
|
@Override
|
||
|
public boolean equals(Object obj) {
|
||
|
System.out.println("equals() called"); // for debugging purposes
|
||
|
if (!(obj instanceof Point3D))
|
||
|
return false;
|
||
|
Point3D p = (Point3D)obj;
|
||
|
if (x != p.x || p.y != y || p.z != z)
|
||
|
return false;
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
@Override
|
||
|
public int hashCode() {
|
||
|
// Just one of many possibilites for a hash code calculation
|
||
|
System.out.println("hashCode() called"); // for debugging purposes
|
||
|
int hash = 0;
|
||
|
hash = 61 * hash + x;
|
||
|
hash = 61 * hash + y;
|
||
|
hash = 61 * hash + z;
|
||
|
return hash;
|
||
|
}
|
||
|
|
||
|
/** main method to test functionality */
|
||
|
public static void main(String [] args) {
|
||
|
// write out a few hash codes
|
||
|
Point3D point;
|
||
|
point = new Point3D();
|
||
|
System.out.println( "hash=" + point.hashCode());
|
||
|
point = new Point3D(1,0,0);
|
||
|
System.out.println( "hash=" + point.hashCode());
|
||
|
point = new Point3D(0,1,0);
|
||
|
System.out.println( "hash=" + point.hashCode());
|
||
|
point = new Point3D(0,0,1);
|
||
|
System.out.println( "hash=" + point.hashCode());
|
||
|
System.out.println();
|
||
|
|
||
|
//check equality and identity
|
||
|
Point3D p1 = new Point3D( 7, 5, 6);
|
||
|
Point3D p2 = p1; // identical
|
||
|
Point3D p3 = new Point3D( 7, 5, 6); // equal
|
||
|
System.out.println( "hash p1=" + p1.hashCode());
|
||
|
System.out.println( "hash p2=" + p2.hashCode());
|
||
|
System.out.println( "hash p3=" + p3.hashCode());
|
||
|
if (p1.equals(p2)) System.out.println("p1 equals p2");
|
||
|
if (p2.equals(p3)) System.out.println("p2 equals p3");
|
||
|
if (p1 == p2) System.out.println( "p1 is identical to p2");
|
||
|
if (p1 == p3) System.out.println( "p1 is identical to p3");
|
||
|
System.out.println();
|
||
|
|
||
|
// Test usage in HashMap
|
||
|
HashMap<Point3D,String> hmap = new HashMap();
|
||
|
hmap.put(p1, "p1"); // stores p1
|
||
|
hmap.put(p2, "p2"); // p2 replaces p1 becaus it's identical
|
||
|
hmap.put(p3, "p3"); // p3 replaces p2 because it's equal
|
||
|
System.out.println("--- hashMapsize=" + hmap.size());
|
||
|
hmap.put(point, "point");
|
||
|
System.out.println("--- hashMapsize=" + hmap.size());
|
||
|
String v1 = hmap.get(p1);
|
||
|
System.out.println("v1=" + v1);
|
||
|
String vv = hmap.get(point);
|
||
|
System.out.println("vv=" + vv);
|
||
|
}
|
||
|
|
||
|
}
|