HashCode in Java

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();
	}
}

Reflection in Java

Person.java

import java.util.Calendar;

public class Person
{
	public String publicString1;
	public String publicString2;
	
	private String fname;
	private String lname;
	protected int birthYear;
	String address;
	String city;
	String state;
	String zipCode;
	
	public Person(String fname, String lname) {
		super();
		this.fname = fname;
		this.lname = lname;
	}
	
	public Person(String fname, String lname, int birthYear) {
		super();
		this.fname = fname;
		this.lname = lname;
		this.birthYear = birthYear;
	}

	public String getFname() {
		return fname;
	}
	public void setFname(String fname) {
		this.fname = fname;
	}
	public String getLname() {
		return lname;
	}
	public void setLname(String lname) {
		this.lname = lname;
	}
	public int getBirthYear() {
		return birthYear;
	}
	public void setBirthYear(int birthYear) {
		this.birthYear = birthYear;
	}
	public int calculateAge()
	{
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.YEAR) - birthYear;
	}
	public void setAddress(String address, String city, String state, String zipCode)
	{
		this.address = address;
		this.city = city;
		this.state = state;
		this.zipCode = zipCode;
	}
	public String toString()
	{
		return fname + " " + lname;
	}
}

Shape.java

public class Shape <T, K> {
	T left;
	T right;
	K top;
	K bottom;

	public Shape(T left, T right, K top, K bottom) {
		this.left = left;
		this.right = right;
		this.top = top;
		this.bottom = bottom;
	}
}

Square.java

public class Square extends Shape {
	public Square(T left, T right, K bottom, K top) {
		super(left, right, top, bottom);
	}
}

Rectangle.java

public class Rectangle extends Shape<Integer, Integer>{
	public Rectangle(Integer left, Integer right, Integer bottom, Integer top) {
		super(left, right, top, bottom);
	}
}

Reflection.java

package com.tutorial;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;

public class Reflection {
	static void AnalyzePerson()
	{
		try {
			Class<?> c = Class.forName("com.tutorial.Person");
			
			//print out all functions in class Person
			Method [] m = c.getDeclaredMethods();
			for(int i = 0; i < m.length; i++)
			{
				System.out.println("Method Name: " + m[i].getName());
				System.out.println("Return Type: " + m[i].getReturnType());
				Class<?>[] t = m[i].getParameterTypes();
				for(int j = 0; j < t.length; j++)
					System.out.println("Parameters: " + t[j].getName());
				
				System.out.println();
			}
			
			//print out all public field in class Person
			Field [] f = c.getDeclaredFields();
			for(int i = 0; i < f.length; i++)
				System.out.println("Fields: " + Modifier.toString(f[i].getModifiers()) + " " + f[i].getName());
			
			System.out.println();
			
			//calls constructor
			Class <?> parameterType[] = {String.class, String.class};
			Constructor<?> ct = c.getConstructor(parameterType);
			Object argList[] = {"John", "Smith"};
			Object newPerson = ct.newInstance(argList);
			System.out.println(((Person)newPerson).toString());
			
			//sets birthday
			Class <?> parameterType1[] = {Integer.TYPE};
			Method m1 = c.getMethod("setBirthYear", parameterType1);
			Object argList1[] = {new Integer(1985)};
			m1.invoke(newPerson, argList1);
			
			//calculate age
			Method m2 = c.getMethod("calculateAge");
			Object ret = m2.invoke(newPerson);
			System.out.println("Age: " + ret);
			System.out.println();
			
			//set field publicString1
			Field field = c.getField("publicString1");
			field.set(newPerson, "Alfred");
			Object obj = field.get(newPerson);
			System.out.println(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	static void AnalyzeSquare()
	{
		System.out.println("----------------------------------------");
		try {
			Class <?> c = Class.forName("com.tutorial.Square");
			//get base class
			Class <?>superc = c.getSuperclass();
			System.out.println("Base Class: " + superc.getName());
			
			//get parameters for square
			Square<Integer, Integer> s = new Square<Integer, Integer>(1, 1, 100, 100);
			ParameterizedType pt = (ParameterizedType)s.getClass().getGenericSuperclass();
			System.out.println(pt);
			
			//get parameters for rectangle
			Rectangle r = new Rectangle(2, 2, 100, 300);
			pt = (ParameterizedType)r.getClass().getGenericSuperclass();
			System.out.println(pt);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args) {
		AnalyzePerson();
		AnalyzeSquare();
	}
}

Events in Java

NumberReaderEvent.java

import java.util.EventObject;

public class NumberReaderEvent extends EventObject {
	
	private static final long serialVersionUID = 1L;

	int value;
	
	public int getValue() {
		return value;
	}
	
	public NumberReaderEvent(Object arg0, int value) {
		super(arg0);
		this.value = value;
	}
}

NumberReaderEventListener.java

import java.util.EventListener;

public interface NumberReaderEventListener extends EventListener{
	public void NumberReaderActionPerformed(NumberReaderEvent e);
}

NumberReader.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class NumberReader {
	Set<NumberReaderEventListener> s = new HashSet<NumberReaderEventListener>();
	
	public void addEventListener(NumberReaderEventListener a)
	{
		s.add(a);
	}
	
	public void removeEventListener(NumberReaderEventListener a)
	{
		s.remove(a);
	}
	
	Integer getInteger(String d)
	{
		Integer temp = null;
		try{
			temp = Integer.valueOf(d);
		}catch (Exception e) {
		}
		return temp;
	}
	
	public void start()
	{
		Integer d = 0;

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		do
		{
			System.out.print("Enter a number: ");
			String readLine = "";
			try {
				readLine = br.readLine();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			d = getInteger(readLine);
			if(d!= null)
			{
				for(NumberReaderEventListener e : s)
				{
					e.NumberReaderActionPerformed(new NumberReaderEvent(this, d));
				}
			}
		}while(d != null);
	}
}

NumberReaderTest.java

public class NumberReaderTest {
	static class multiply implements NumberReaderEventListener
	{
		int total = 1;
		@Override
		public void NumberReaderActionPerformed(NumberReaderEvent e) {
			total = total * e.getValue();
			System.out.println("multiplying " + e.getValue() + ". Total: " + total);
		}
		
	}
	
	static class add implements NumberReaderEventListener
	{
		int total = 0;
		@Override
		public void NumberReaderActionPerformed(NumberReaderEvent e) {
			total = total + e.getValue();
			System.out.println("adding " + e.getValue() + ". Total: " + total);
		}
		
	}
	
	public static void main(String[] args) {
		NumberReader r = new NumberReader();
		multiply m = new multiply();
		add a = new add();
		r.addEventListener(new NumberReaderEventListener() {
			
			@Override
			public void NumberReaderActionPerformed(NumberReaderEvent e) {
				System.out.println(e.getValue() + " received.");
			}
		});
		r.addEventListener(m);
		r.addEventListener(a);
		r.start();
		
		System.out.println("\n\nRemoving multiply and add listener");
		r.removeEventListener(m);
		r.removeEventListener(a);
		r.start();
	}
}

Callbacks in Java

CallbackInterface.java

public interface CallbackInterface {
	void CallWhenDone();
}

ClassB.java

public class ClassB {
	CallbackInterface callback;

	public void DoingSomething()
	{
		System.out.println("Doing something for 2 seconds");
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		callback.CallWhenDone();
	}

	public void setCallback(CallbackInterface c)
	{
		callback = c;
	}
}

ClassA.java

public class ClassA implements CallbackInterface {

	@Override
	public void CallWhenDone() {
		System.out.println("I am all done!");
	}

	public void doSomething()
	{
		ClassB b = new ClassB();
		b.setCallback(this);
		b.DoingSomething();
	}
	public static void main(String[] args) {
		ClassA a = new ClassA();
		a.doSomething();
	}
}