網頁

2014年3月14日 星期五

Commons Lang使用CompareToBuilder

當implement Comparable時,是需要實作compareTo(),Apache Commons Lang 提供了CompareToBuilder類別,能夠快速地實作compareTo(),只要建構CompareToBuilder實例,並append所需要的field,就可以得到結果。






Mix加上@Override註解,確定正確地覆寫compareTo(),然後用CompareToBuilder來排序兩個物件的field值,因為Mix想用id來作為排序,所以用getId()取值,最後記得呼叫toComparison()取傳回值。

package org.openyu.java.commons.lang;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 * The Class Book.
 */
                             //支援比較
public class Book implements Comparable<book> {

 /** The id. */
 private long id;

 /** The name. */
 private String name;

 /**
  * Instantiates a new book.
  */
 public Book() {
 }

 /**
  * Gets the id.
  *
  * @return the id
  */
 public long getId() {
  return id;
 }

 /**
  * Sets the id.
  *
  * @param id
  *            the new id
  */
 public void setId(long id) {
  this.id = id;
 }

 /**
  * Gets the name.
  *
  * @return the name
  */
 public String getName() {
  return name;
 }

 /**
  * Sets the name.
  *
  * @param name
  *            the new name
  */
 public void setName(String name) {
  this.name = name;
 }

 /*
  * (non-Javadoc)
  *
  * @see java.lang.Comparable#compareTo(java.lang.Object)
  */
 public int compareTo(Book o) {
  return new CompareToBuilder()
  .append(this.getId(), o.getId())
  .toComparison();
 }
}






Mix撰寫一些測試程式碼,來檢查看看,是否符合預期,id排序應為{1,2,3}。

package org.openyu.java.commons.lang;

import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.Test;

/**
 * The Class BookTest.
 */
public class BookTest {

 /**
  * Compare to.
  */
 @Test
 public void compareTo() {
  Book book = new Book();
  book.setId(1);
  book.setName("OpenYu");
  //
  Book book2 = new Book();
  book2.setId(2);
  book2.setName("OpenYu");
  //
  int result = book.compareTo(book2);
  System.out.println(result);
  assertEquals(-1, result);
  //

  Book book3 = new Book();
  book3.setId(3);
  book3.setName("Java");
  //
  Book[] books = new Book[] { book2, book, book3 };
  System.out.println("before sort: ");
  for (Book r : books) {
   System.out.println(r);
  }
  //
  System.out.println();
  Arrays.sort(books);
  System.out.println("after sort: ");
  for (Book r : books) {
   System.out.println(r);
  }
  //
  assertEquals(1, books[0].getId());
  assertEquals(2, books[1].getId());
  assertEquals(3, books[2].getId());
 }
}






測試成功了,符合Mix的預期。




console查看其結果。

-1
before sort: 
Book[id=2,name=OpenYu]
Book[id=1,name=OpenYu]
Book[id=3,name=Java]

after sort: 
Book[id=1,name=OpenYu]
Book[id=2,name=OpenYu]
Book[id=3,name=Java]



沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...