import java.util.Hashtable;
import java.util.Random;
public class HashCode {
static class Person
{
public Person(String fname, String lname) {
this.fname = fname;
this.lname = lname;
}
String fname;
String lname;
public int hashCode()
{
return (fname.hashCode() * 1021) ^ lname.hashCode();
}
public boolean equals(Object obj)
{
return this.fname.equals(((Person)obj).fname) &&
this.lname.equals(((Person)obj).lname);
}
}
static class Point
{
public Point(int x, int y) {
this.x = x;
this.y = y;
}
int x;
int y;
public int hashCode()
{
return (x * 31) ^ y;
}
public boolean equals(Object obj)
{
return x == ((Point)obj).x &&
y == ((Point)obj).y;
}
}
static Character [] getLowerCase()
{
Character []temp = new Character[26];
for(int i = 0; i < 26; i++)
temp[i] = (char)(i + 97);
return temp;
}
static Character [] getUpperCase()
{
Character []temp = new Character[26];
for(int i = 0; i < 26; i++)
temp[i] = (char)(i + 65);
return temp;
}
static String getName(Character[] lower, Character[] upper)
{
Random r = new Random();
StringBuilder sb = new StringBuilder();
int count = r.nextInt(10);
for(int j = 0; j < count; j++)
{
int index = r.nextInt(25);
if(j == 0)
sb.append(upper[index]);
else
sb.append(lower[index]);
}
return sb.toString();
}
static void AnalyzePerson()
{
Character [] lower = getLowerCase();
Character [] upper = getUpperCase();
Hashtable<Person, Integer> table = new Hashtable<Person, Integer>();
Person []list = new Person[500000];
long pastTime = System.currentTimeMillis();
for(int i = 0; i < 500000; i++)
{
String fname = getName(lower, upper);
String lname = getName(lower, upper);
Person p = new Person(fname, lname);
table.put(p, i);
list[i] = p;
}
long currentTime = System.currentTimeMillis();
System.out.println("putting: " + (currentTime - pastTime));
pastTime = System.currentTimeMillis();
for(int i = 0; i < 500000; i++)
{
Person p = list[i];
table.get(p);
}
currentTime = System.currentTimeMillis();
System.out.println("getting: " + (currentTime - pastTime));
}
static void AnalyzePoint()
{
Hashtable<Point, Integer> table = new Hashtable<Point, Integer>();
Point []list = new Point[500000];
Random r = new Random();
long pastTime = System.currentTimeMillis();
for(int i = 0; i < 500000; i++)
{
Point p = new Point(r.nextInt(50), r.nextInt(100));
table.put(p, i);
list[i] = p;
}
long currentTime = System.currentTimeMillis();
System.out.println("putting: " + (currentTime - pastTime));
pastTime = System.currentTimeMillis();
for(int i = 0; i < 500000; i++)
{
Point p = list[i];
table.get(p);
}
currentTime = System.currentTimeMillis();
System.out.println("getting: " + (currentTime - pastTime));
}
public static void main(String[] args) {
AnalyzePoint();
AnalyzePerson();
}
}