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;
}
分享到:
相关推荐
Volume II–Advanced Features, covers advanced user-interface programming and the enterprise features of the Java SE 6 platform. Like Volume I (which covers the core language and library features), ...
You'll also find coverage of some of Java's most advanced features, including multithreaded programming and generics. An introduction to Swing concludes the book. Get started programming in Java ...
As a teacher, has taken over 1,000 hours of training in basic Java, J2EE, and the Struts framework. As a researcher, he has worked in the field of information retrieval, developing applications for ...
Learn Scala is split into four parts: a tour of Scala, a comparison between Java and Scala, Scala-specific features and functional programming idioms, and finally a discussion about adopting Scala in...
It features hundreds of complete Java 9 programs with thousands of lines of proven code, and hundreds of software-development tips that will help you build robust applications. Start with an ...
The book features 220 Java applications with over 18,000 lines of proven Java code, and hundreds of tips that will help you build robust applications. Start with an introduction to Java using an ...
The book features 200+ C# applications with 17,000+ lines of proven C# code, as well as hundreds of programming tips that will help you build robust applications. Start with a concise introduction ...
#### 1. Introduction to PL/SQL PL/SQL (Procedural Language for SQL) is a procedural extension to SQL that provides a powerful way to manipulate data within the Oracle database environment. This ...
If you are a Java developer who has little or no experience in JEE application development or you have experience in JEE technology but are looking for tips to simplify and accelerate your development...
All you need is a basic knowledge of Java programming, and this book will show you how to turn your ideas into games and sell them on BlackBerry App World (Figure 1-1) and beyond!
Chapter 1. Getting Started Hello Qt Making Connections Laying Out Widgets Using the Reference Documentation Chapter 2. Creating Dialogs Subclassing QDialog Signals and Slots in Depth ...
- **C++ Compared with Java:** Compares C++ with Java, highlighting differences in syntax and features. ### Chapter 2: Native Types and Statements Chapter 2 delves deeper into the native types and ...
including C#, C++, C, Java™, Android™ app development, iOS app development, Swift™, Visual Basic®, Python™ and Internet and web programming. Features: Use with Windows® 7, 8 or 10. Integrated...
Title: Android Games Practical Programming By Example: Quickstart 1 (Volume 1) Author: Fred Yang Length: 140 pages Edition: 1 Language: English Publisher: CreateSpace Independent Publishing Platform ...
The book features 200+ C# applications with 17,000+ lines of proven C# code, as well as hundreds of programming tips that will help you build robust applications. Start with a concise introduction ...
Groovy in Action is a comprehensive guide to Groovy programming, introducing Java developers to the new dynamic features that Groovy provides. To bring you Groovy in Action, Manning again went to the...