JAVA Programming - Tips 1 - Features

1. Class Initialization Order
package com.ross.test.j2ee.exam;
class A {
	static {
		System.out.print("1");
	}

	public A() {
		System.out.print("2");
	}
}
class B extends A {
	static {
		System.out.print("a");
	}

	public B() {
		System.out.print("b");
	}
}
public class ClassOrder {
	public static void main(String[] ars) {
		A ab = new B(); //  1a2b
		ab = new B(); // 1a2bab
	}
}


2. Sort & Comparing
2.1 Specialized Sort
public class SortArrayList {
	static ArrayList al;
	public SortArrayList(int num, int mod) {
		al = new ArrayList(num);
		Random rand = new Random();
		System.out.println("The ArrayList Sort Before:");
		for (int i = 0; i < num; i++) {
			al.add(new Integer(Math.abs(rand.nextInt()) % mod + 1));
			System.out.println("al[" + i + "]=" + al.get(i));
		}
	}
	
	/**
	 * function: make parameter ArrayList al sorted ascend 
	 * @param al
	 */
	public void SortIt(ArrayList al) {
		Integer tempInt;
		int MaxSize = 1;
		for (int i = 1; i < al.size(); i++) {
			tempInt = (Integer) al.remove(i);
			if (tempInt.intValue() >= ((Integer) al.get(MaxSize - 1)).intValue()) {
				al.add(MaxSize, tempInt);
				MaxSize++;
				System.out.println(al.toString());
			} else {
				for (int j = 0; j < MaxSize; j++) {
					if (((Integer) al.get(j)).intValue() >= tempInt.intValue()) {
						al.add(j, tempInt);
						MaxSize++;
						System.out.println(al.toString());
						break;
					}
				}
			}
		}
		System.out.println("The ArrayList Sort After:");
		for (int i = 0; i < al.size(); i++) {
			System.out.println("al[" + i + "]=" + al.get(i));
		}
	}

	public static void main(String[] args) {
		SortArrayList is = new SortArrayList(10, 100);
		is.SortIt(al);
	}
}

2.2 Sort By comparator
Comparator:A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap).

Comparable:This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method
.


package com.ross.j2ee.exam;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

/**
 * @file ComparatorDemo.java
 * @function The <code>ComparatorDemo.java</code> ......
 * @version: 1.0.0
 * @author: Ross Bu
 * @Created: 2008-9-23
 */

class User {
	String name;

	String age;

	public User(String name, String age) {
		this.name = name;
		this.age = age;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}// ComparatorDemo

/**
 * Comparator 1
 * 
 * @author Ross Bu
 * 
 */
class ComparatorUser implements Comparator {

	public int compare(Object arg0, Object arg1) {
		User user0 = (User) arg0;
		User user1 = (User) arg1;
		// Age then Name
		int flag = user0.getAge().compareTo(user1.getAge());
		if (flag == 0) {
			return user0.getName().compareTo(user1.getName());
		} else {
			return flag;
		}
	}
}

/**
 * Comparator 2 to make Integer implement comparing between absolute values
 * 
 * @author Ross bu
 * 
 */
class AbsComparator implements Comparator {
	public int compare(Object o1, Object o2) {
		int v1 = Math.abs(((Integer) o1).intValue());
		int v2 = Math.abs(((Integer) o2).intValue());
		return v1 > v2 ? 1 : (v1 == v2 ? 0 : -1);
	}
	/*  JDK implementation for Integer comparing between two Integer Regardless negtive number or positive number
	 *  JDK Class String and Integer all have implementated Comparable interface 
	 *  <code>
	 *     public int compareTo(Integer anotherInteger) {
			int thisVal = this.value;
			int anotherVal = anotherInteger.value;
			return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
			}
		</code>
    }
	 */
}

public class ComparatorDemo {

	public static void main(String[] args) {
		System.out.println("########################### Below code for Comparator User #################");
		List userlist = new ArrayList();
		userlist.add(new User("dd", "4"));
		userlist.add(new User("aa", "1"));
		userlist.add(new User("ee", "5"));
		userlist.add(new User("bb", "2"));
		userlist.add(new User("ff", "5"));
		userlist.add(new User("cc", "3"));
		userlist.add(new User("gg", "6"));

		ComparatorUser comparator = new ComparatorUser();
		Collections.sort(userlist, comparator);// sorted here

		for (int i = 0; i < userlist.size(); i++) {
			User temp = (User) userlist.get(i);
			System.out.println(temp.getAge() + "," + temp.getName());
		}

		System.out.println("########################### Below code for Integer Comparator #################");
	      Random   rnd   =   new   Random();
	      Integer[]   integers   =   new   Integer[20];
	      for(int   i   =   0;   i   <   integers.length;   i++)
	      integers[i]   =   new   Integer(rnd.nextInt(100)   *   (rnd.nextBoolean()   ?   1   :   -1));

	      System.out.println(" Using Integer default Comparator:");
	      Arrays.sort(integers);
	      System.out.println(Arrays.asList(integers));

	      System.out.println(" Using Personalized Comparator (AbsComparator)");
	      Arrays.sort(integers,   new   AbsComparator());
	      System.out.println(Arrays.asList(integers));
		
	}
}

2.3 Comparable Interface in use
2.3.1 Declaration
public class Model implements Serializable, Comparable{
        int id;
        public Model(int id){
        this.id=id;
        }
	public int compareTo(Object o) {
		return String.valueOf(id).compareTo(String.valueOf(((Model) o).id));
	}
}

2.3.2 Invokation
ArrayList al = new ArrayList();
al.add(new Model(1));
al.add(new Model(2));
Collections.sort(al);


2.4 equals for two object comparation
    public boolean equals(Object obj) {
        return (obj instanceof Person) && this.id == ((Person) obj).id;
    }

	public boolean equals(Object o) {
		if (this == o)
			return true; // the same object
		if (o == null || getClass() != o.getClass())
			return false;
		final Model model = (Model) o;
		if (id == model.getId())
			return true;
		else
			return false;
	}

你可能感兴趣的:(java,jdk,J#)