排序的算法是我们最常用的算法,初学E序Q每个h都尝试过排序。但只是局限于单的排序?br />如将下列数字q行排序
1Q?Q?Q?Q?Q?
于是我们得出l果
1Q?Q?Q?Q?Q?
下列字母(字符Q进行排?br />a,i,e,f,w,s
于是我们得出l果
a,e,f,i,s,w
但是我们遇到的情况就不是如此单了。如l公叔R的商品进行排序,我们很轻易的惛_按照商品的名U排序不完了,而且单明了。但现实q如我们怿般简单。同一商品名称可以有不同的ҎQ进货时_可能q会有单L不同。显然只Ҏ商品名称排序是不合理的?br />
再D个简单例子然后用E序实现。如公司要将员工q行排序Q不要说领导排在前面Q,假设我们的需求比较复杂。先q行姓排序,谁的姓拼音靠前,谁就排前面。然后对名字q行排序。恩.如果同名Q女性排前头。如果名字和性别都相同,q龄的排前头。okQ一个也不算复杂的需求?br />
如果对java比较熟悉的会知道java.util.Comparator 接口。要实现里面的函?br /> int compare(Object o1, Object o2) q回一个基本类型的整型Q返回负数表Co1 于o2Q返? 表示o1和o2相等Q返回正数表Co1大于o2?br />
于是我们设计的h员类要有几个变量Qfirstname,lastname,sex,age分别表示姓,名,性别Q年龄?br />
public class Person {
String firstname,lastname;
Boolean sex;
Integer age;
public Person(String firstname,String lastname,Boolean sex,Integer age) {
this.firstname = firstname;
this.lastname = lastname;
this.sex = sex;
this.age = age;
}
public String getFirstName() {
return firstname;
}
public String getLastName() {
return lastname;
}
public Boolean getSex() {
return sex;
}
public Integer getAge() {
return age;
}
//Z输入方便Q重写了toString()
public String toString()
{
return firstname +" "+lastname+" "+(sex.booleanValue()?"?:"?)+" "+age;
}
}
//end person
下面是要实现比较?br />
public class Comparators {
public static java.util.Comparator getComparator() {
return new java.util.Comparator() {
public int compare(Object o1, Object o2) {
if (o1 instanceof String) {
return compare( (String) o1, (String) o2);
}
else if (o1 instanceof Integer) {
return compare( (Integer) o1, (Integer) o2);
}
else if (o1 instanceof Person) {
return compare( (Person) o1, (Person) o2);
}
else {
System.err.println("未找到合适的比较?);
return 1;
}
}
public int compare(String o1, String o2) {
String s1 = (String) o1;
String s2 = (String) o2;
int len1 = s1.length();
int len2 = s2.length();
int n = Math.min(len1, len2);
char v1[] = s1.toCharArray();
char v2[] = s2.toCharArray();
int pos = 0;
while (n-- != 0) {
char c1 = v1[pos];
char c2 = v2[pos];
if (c1 != c2) {
return c1 - c2;
}
pos++;
}
return len1 - len2;
}
public int compare(Integer o1, Integer o2) {
int val1 = o1.intValue();
int val2 = o2.intValue();
return (val1 < val2 ? -1 : (val1 == val2 ? 0 : 1));
}
public int compare(Boolean o1, Boolean o2) {
return (o1.equals(o2)? 0 : (o1.booleanValue()==true?1:-1));
}
public int compare(Person o1, Person o2) {
String firstname1 = o1.getFirstName();
String firstname2 = o2.getFirstName();
String lastname1 = o1.getLastName();
String lastname2 = o2.getLastName();
Boolean sex1 = o1.getSex();
Boolean sex2 = o2.getSex();
Integer age1 = o1.getAge();
Integer age2 = o2.getAge();
return (compare(firstname1, firstname2) == 0 ?
(compare(lastname1, lastname2) == 0 ? (compare(sex1, sex2) == 0 ? (compare(age1, age2) == 0 ? 0 :
compare(age1, age2)) :
compare(sex1, sex2)) :
compare(lastname1, lastname2)) :
compare(firstname1, firstname2));
}
};
}
}
以上代码有可能因为浏览器的布局自动换行?br />compare(Person o1, Person o2)的返回值看h比较别扭。最单的?br />
public int compare(Boolean o1, Boolean o2) {
return (o1.equals(o2)? 0 : (o1.booleanValue()==true?1:-1));
}
o1和o2相等q回0Q否则o1如果是true pCo1大于o2?br />
再尝试输出结果看?br />
public class Main {
public Main() {
}
public static void main(String[] args) {
Person[] person = new Person[] {
new Person("ouyang", "feng", Boolean.TRUE, new Integer(27)),
new Person("zhuang", "gw", Boolean.TRUE, new Integer(27)),
new Person("zhuang", "gw", Boolean.FALSE, new Integer(27)),
new text.Person("zhuang", "gw", Boolean.FALSE, new Integer(2)),
};
for (int i = 0; i < person.length; i++) {
System.out.println("before sort=" + person[i]);
}
java.util.Arrays.sort(person, Comparators.getComparator());
for (int i = 0; i < person.length; i++) {
System.out.println("after sort=" + person[i]);
}
}
}
输出l果Q?br />
before sort=ouyang feng ?27
before sort=zhuang gw ?27
before sort=zhuang gw ?27
before sort=zhuang gw ?2
after sort=ouyang feng ?27
after sort=zhuang gw ?2
after sort=zhuang gw ?27
after sort=zhuang gw ?27
仔细理解java的Comparator会给你写排序带来很大帮助
Google Web Toolkit (GWT) is a Java software development framework that makes writing AJAX applications like Google Maps and Gmail easy for developers who don't speak browser quirks as a second language. Writing dynamic web applications today is a tedious and error-prone process; you spend 90% of your time working around subtle incompatabilities between web browsers and platforms, and JavaScript's lack of modularity makes sharing, testing, and reusing AJAX components difficult and fragile.
GWT lets you avoid many of these headaches while offering your users the same dynamic, standards-compliant experience. You write your front end in the Java programming language, and the GWT compiler converts your Java classes to browser-compliant JavaScript and HTML.
and there is a feedback that it's not better than dojo.
引自Q?a >http://www-900.ibm.com/developerWorks/cn/java/jw-tips/tip010/
作者:John D. Mitchell
摘要
?Java 支持Ҏ指针之前QJava 接口不能提供一U实现回调的好方法。如果您习惯于传递在事g驱动~程模型中调用的函数指针Q则您会喜欢本技巧?br />熟悉 MS-Windows ?X Window System 事g驱动~程模型的开发h员,习惯于传递在某种事g发生时调用(即“回调”)的函数指针。Java 的面向对象模型目前ƈ不支持方法指针,q样g׃可能使用q种很好的机制。但我们q不是一点办法都没有Q?
Java 的接口支持提供了一U获得回调的{h功能的机制。其技巧就是:定义一个简单接口,q在该接口中声明我们要调用的Ҏ?/p>
例如Q假定我们希望在某个事g发生时得到通知。我们可以定义一个接口:
public interface InterestingEvent{
// q仅是一个常规方法。因此如果需要,
// 它可有返回|也可接收参数?br />public void interestingEvent ();
}
q得我们可以控制实现该接口的类的Q何对象。因此,我们不必兛_M外部cd信息。与在将 C++ 代码用于 Motif 时用窗口小部g的数据域来容U_象指针的难以控制?C 函数相比Q这U方法要好得多?/p>
发出事g信号的类必须{待实现?InterestingEvent 接口的对象,q在适当时候调?interestingEvent() Ҏ?/p>
public class EventNotifier{
private InterestingEvent ie;
private boolean somethingHappened;
public EventNotifier (InterestingEvent event){
// 保存事g对象以备后用?br />ie = event;
// q没有要报告的事件?br />somethingHappened = false;
}
//...
public void doWork (){
// 查在别处讄的谓词?br />if (somethingHappened){
// 通过调用接口的这个方法发Z件信受?br />ie.interestingEvent ();
}
//...
}
// ...
}
在上例中Q我使用 somethingHappened 谓词来跟t是否应触发事g。在许多情况下,调用此方法以保证向 interestingEvent() 发出信号?/p>
希望接收事g通知的代码必d?InterestingEvent 接口Qƈ自w引用传递给事g通知E序?/p>
public class CallMe implements InterestingEvent{
private EventNotifier en;
public CallMe (){
// 创徏事g通知E序Qƈ自w引用传递给它?br />en = new EventNotifier (this);
}
// Z件定义实际的处理E序?br />public void interestingEvent (){
// 噢!必定发生了感兴趣的事Ӟ
// 执行某些操作 ...
}
//...
}
q就是所要做的全部工作。我希望q个单的 Java 习惯用法会您更有信心地转向 Java?/p>
JavaWorld q有一个名?Java Questions & Answers 特色专栏Q现在就有?Java 语言的问题发送到 javaqa@javaworld.com?我们也希望将您的 Java 技巧刊d以后?Java world 上。赶快将您最的技巧和H门写出?-- 参加 JavaWorld ?"Java Tip of the Week" 竞赛?如果您的 Java 技巧成?JavaWorld "Java Tip of the Week"Q您获?JavaWorld 奖励的一?T 恤,以及一周的荣誉和声望。请您?Java 技巧和H门发送到 javatips@javaworld.com?/p>
作者简?br />John D. Mitchell 在过Mq的大部分时间里一直在 Geoworks 从事N工作Qƈ用面向对象的汇编语言开发了 PDA 软g。他睡眠很少Q靠咖啡因和p维持着。他通过~写~译器、Tcl/Tk?C++ ?Java pȝ支助着自己?Java 嗜好。John D. Mitchell q参与编写了一本畅销?Java 著作QMaking Sense of JavaQ目前正在开发一U?Java ~译器?/p>
目名称 | 目描述转蝲?/font>http://andyluo.blogjava.net | |||
---|---|---|---|---|
ASM | Java bytecode manipulation framework | |||
AspectWerkz | AspectWerkz - Dynamic AOP for Java | |||
Axis | Axis - an implementation of the SOAP (Simple Object Access Protocol) submission to W3C | |||
Batik | Batik SVG Toolkit - Toolkit using images in the Scalable Vector Graphics (SVG) format | |||
BCEL | Byte Code Engineering Library - Analyze, create and manipulate Java class files | |||
BeanUtils | BeanUtils - Utilities for working with JavaBeans | |||
Catalina | Catalina - Servlet and JSP based web server | |||
Cayenne | Professional Object Relational Mapping | |||
CGLIB | CGLIB - Dynamic byte code generator转蝲?/font>http://andyluo.blogjava.net | |||
Chain | Chain - Implementation of the GoF "Chain of Responsibility" pattern | |||
Checkstyle | Checkstyle - Development tool to help writing Java code that adheres to a coding standard | |||
CLI | Command Line Library - Simple API for working with the command line arguments and options | |||
Codec | Commons Codec - Encoders and decoders like Base64, Hex, phonetic encodings and URLs | |||
Collections | Collections - Filling the holes left in Sun's Collections API | |||
Configuration | Commons Configuration - Generic API enabling configuration from a variety of sources | |||
DBCP | DBCP - Connection pooling implementations | |||
DBUtils | DbUtils - Set of classes designed to make working with JDBC easier | |||
Digester | Struts Digester - Configure an XML/Java mapping with actions when patterns are recognized | |||
Discovery | Discovery - Discovering, or finding, implementations for pluggable interfaces | |||
DNSJava | DNS in Java - Supporting common record types, queries, zone transfers and dynamic updates | |||
doclet | JavaDoc Doclet - Custom output from the types methods and fields in a source tree. | |||
Dom4j | DOM4J - XML, XPath and XSLT library | |||
DTDParser | DTDParse DTD Library - You can use this library to parse a DTD | |||
EL | EL - The JSP 2.0 Expression Language Interpreter from Apache | |||
fastutil | FastUtil - Type-specific maps sets and lists with a small memory footprint and fast access | |||
FileUpload | HTTP File Upload Library - Add robust, fast file upload capability to your web applications | |||
FreeMarker | HTML Template Enginehttp://andyluo.blogjava.net | |||
GJT | Giant Java Tree - Java library consisting entirely of open source components | |||
gnu-regex | GNU Regular Expressions - Implementation of a traditional (non-POSIX) NFA regex engine | |||
Groovy | Groovy - Scripting Language | |||
GlassFish | an oo app server implements JavaEE 5 | |||
Hibernate | Hibernate - Relational Persistence For Idiomatic Java | |||
HiveMind | HiveMind - A services and configuration microkernel | |||
HSQLDB | HSQLDB - The Java SQL relational database | |||
HTMLParser | HTML Parser - Java library used to parse HTML | |||
HTTPClient | HTTP Client - Fills holes left by the java.net package, including most recent HTTP standards | |||
Informa | Informa - News aggregation library --- LGPL协议 | |||
IO | Commons-IO - Utility classes, stream implementations, file filters and endian classes for IO | |||
iText | iText - Generates PDF on the fly | |||
J2EE | Java 2 Platform, Enterprise Edition | |||
J2SE | Java2 Standard Edition v5http://www.aygfsteel.com/Andyluo/archive/2006/04/15/javaprojects.html | |||
JAI | Java Advanced Imaging - Network-enabled, scalable, platform-independent image processing | |||
Jalopy | Jalopy Source Formatter - Formats Java source code according to widely configurable rules | |||
Jasper | Jasper - Tomcat JSP enginehttp://andyluo.blogjava.net | |||
JasperReports | JasperReports - Free Java reporting library | |||
Java3d | Java3D - Object-oriented interfaces that support a simple, high-level programming mode | |||
JavaComm | Java Communications - API for technologies such as voice mail, fax and smartcards | |||
JavaGroups | JavaGroups - Reliable multicast communication enable processes to send messages to each other | |||
Jaxen | Jaxen XPath Processor - Object model walker; evaluate XPath expressions in dom4j and JDOM | |||
JAXME | JaxMe 2 - Open source implementation of JAXB | |||
JClassLib | JClassLib - Library for reading, modifing and writing Java class files and bytecode | |||
JCommon | JCommon - Collection of useful classes used by JFreeChart, JFreeReport and other projects | |||
JCrontab | JCronTab - Scheduler written in Java, provide a fully functional schedules for Java projects | |||
JDIC | JDIC - JDesktop Integration Components | |||
JDNC | JDNC - JDesktop Network Components | |||
JDO | Java Data Objects - Direct storage of Java domain model instances into a database | |||
JDOM | JDOM XML Library - For accessing, manipulating and outputting XML data from Java code. | |||
JetSpeed | JetSpeed - Java Portal Serverhttp://www.aygfsteel.com/Andyluo/archive/2006/04/15/javaprojects.html | |||
JEXL | Java Expression Language - is an embedable expression language engine | |||
JFreeChart | JFreeChart - Free library for generating charts, including pie, bar, line and areas charts | |||
JGroups | JGroups - Multicast communication toolkit | |||
JMeter | JMeter - Load testing applcation | |||
JMF | Java Media Framework - Library for audio, video and other time-based media | |||
JMock | JMock - Testing libraryhttp://www.aygfsteel.com/Andyluo/archive/2006/04/15/javaprojects.html | |||
JSF | JavaServer Faces - Web Framework | |||
JSword | JSword - Bible software in Java, compatible with the Sword project for C/C++ | |||
JTidy | JTidy - HTML syntax checker | |||
JUnit | JUnit - Regression testing framework used by the developer who implements unit tests in Java | |||
JXPath | JXPath Library - Simple interpreter of an expression language called XPath | |||
Lang | Lang - Utilities including Enums, String manipulation, reflection, serialization and more | |||
Log4J | Log4J - Fast logging API that lets you configure logging at runtime | |||
Logging | Commons Logging - Simple wrapper API around multiple logging APIs | |||
Lucene | Lucene - high-performance, full-featured text search engine written entirely in Java | |||
Math | Math - Library of lightweight, self-contained mathematics and statistics components | |||
Net | Network Library - Support for Finger, Whois, TFTP, Telnet, FTP, NNTP, etc developed by ORO | |||
OJB | OJB - O/R tool that allows transparent persistence | |||
OpenJMS | Open source JMS server | |||
ORO | ORO - Text processing library | |||
OSCache | OSCache - A high performance J2EE caching framework | |||
PJA | Pure Java AWT - Toolkit for drawing graphics without any native graphics resources | |||
PMD | PMD - Scans Java source code for potential problems | |||
POI | POI - Java OLE 2 Manipulator | |||
Pool | Commons Pooling - provides an generic, configurable Object-pooling API | |||
Primitives | Primitives - Collection of types and utilities optimized for working with Java primitives | |||
Proxool | Java connection pool | |||
Quartz | Quartz - J2EE open source job scheduler | |||
Regexp | Jakarta Regular Expressions - Java RegEx library under BSD style license | |||
Rhino | Mozilla JavaScript - open-source implementation of JavaScript written entirely in Java | |||
Seraph | Seraph - Atlassian Security Framework | |||
SiteMesh | A web-page layout and decoration framework | |||
Slide | Slide - Content repository, can serve as a basis for CMS | |||
SOAP | Apache Soap - implementation of the SOAP submission to W3C | |||
Speedo | OSS JDO implementation转蝲?/font>http://andyluo.blogjava.net | |||
Spring | Server Side alternative to J2EE APIs | |||
Struts | Jakarta Struts - open source framework for building web applications | |||
Tapestry | Tapestry - Web Framework | |||
Turbine | Turbine - Servlet based framework allowing developers to quickly build secure web applications | |||
UDDI4J | UDDI4J - Library that provides an API to interact with a UDDI registry | |||
Validator | Validtator - Validate data from user input | |||
Velocity | Velocity - Support for clean, quick MVC web development and support for the Struts framework | |||
Village | Village - API that sits on top of the JDBC to make it easier to interact with a JDBC | |||
WebWork 2 | Next generation of WebWork | |||
Xalan | Xalan - XSLT processor for transforming XML documents into HTML, text, or XML | |||
XDoclet | XDoclet - Code generation engine | |||
Xerces | Xerces2 - The next generation of high performance, XML parsers in the Apache Xerces family | |||
XMLBeans | XMLBeans - XML-Java binding tool转蝲?/font>http://andyluo.blogjava.net | |||
XMLPull | XMLPull - Defines a simple pull parsing API that does pull XML parsing from J2ME to J2EE | |||
XMLRPC | XML-RPC - Implementation of XML-RPC, using XML over HTTP to implement remote procedure calls | |||
XNI | Xerces Native Interface - Framework for streaming a document and constructing generic parsers | |||
XOM | XML Object Model - Tree-based API for processing XML that strives for correctness and simplicity. | |||
XStream | XML serialization |