標籤:wot 種類 extend html 元素 源碼 資訊 end proc
轉自連結:http://www.cnblogs.com/davidwang456/p/4514659.html
一、為什麼使用元組tuple?
元組和列表list一樣,都可能用於資料存放區,包含多個資料;但是和列表不同的是:列表只能儲存相同的資料類型,而元組不一樣,它可以儲存不同的資料類型,比如同時儲存int、string、list等,並且可以根據需求無限擴充。
比如說在web應用中,經常會遇到一個問題就是資料分頁問題,查詢分頁需要包含幾點資訊:當前頁數、頁大小;查詢結果返回資料為:當前頁的資料記錄,但是如果需要在前台顯示當前頁、頁大小、總頁數等資訊的時候,就必須有另外一個資訊就是:資料記錄總數,然後根據上面的資訊進行計算得到總頁數等資訊。這個時候查詢某一頁資訊的時候需要返回兩個資料類型,一個是list(當前也的資料記錄),一個是int(記錄總數)。當然,完全可以在兩個方法、兩次資料庫連接中得到這兩個值。事實上在查詢list的時候,已經通過sql查詢得到總計錄數,如果再開一個方法,再做一次資料庫連接來查詢總計錄數,不免有點多此一舉、浪費時間、浪費代碼、浪費生命。言重了~在這種情況下,我們就可以利用二元組,在一次資料庫連接中,得到總計錄數、當前頁記錄,並儲存到其中,簡單明了!
二、源碼執行個體
二元組:
| 1234567891011121314151617 |
/** <p>Title: TwoTuple</p> * <p>Description: 兩個元素的元組,用於在一個方法裡返回兩種類型的值</p> * @author [email protected] * @site http://wzwahl36.net * @version 2012-3-21 上午11:15:03 * @param <A> * @param <B> */public class TwoTuple<A, B> { public final A first; public final B second; public TwoTuple(A a, B b) { this.first = a; this.second = b; }} |
擴充為三元組(按此可以任意擴充)
| 123456789101112131415161718 |
/** * <p>Title: ThreeTuple</p> * <p>Description: 三個元素的元組,用於在一個方法裡返回三種類型的值</p> * @author [email protected] * @site http://wzwahl36.net * @version 2012-3-21 上午11:15:50 * @param <A> * @param <B> * @param <C> */public class ThreeTuple<A, B, C> extends TwoTuple<A, B> { public final C third; public ThreeTuple(A a, B b, C c) { super(a, b); this.third = c; }} |
元組操作工具類、測試類別(可按需自訂)
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
import java.util.ArrayList;import java.util.List; import com.bluesea.bean.GoodsBean; /** * <p>Title: TupleUtil</p> * <p>Description: * 元組輔助類,用於多種類型值的返回,如在分頁的時候,後台預存程序既返回了查詢得到的 * 當頁的資料(List類型),又得到了資料表中總共的資料總數(Integer類型),然後將這 * 兩個參數封裝到該類中返回到action中使用 * 使用泛型方法實現,利用參數類型推斷,編譯器可以找出具體的類型 * </p> * @author [email protected] * @site http://wzwahl36.net * @version 2012-3-21 上午09:59:39 * @param <A> * @param <B> */public class TupleUtil { public static <A, B> TwoTuple<A, B> tuple(A a, B b) { return new TwoTuple<A, B>(a, b); } public static <A, B, C> ThreeTuple<A, B, C> tuple(A a, B b, C c) { return new ThreeTuple<A, B, C>(a, b, c); } // 測試 public static void main(String[] args) { List<GoodsBean> goodsBeans = new ArrayList<GoodsBean>(); for(int i = 1; i < 26; i++) { GoodsBean goodsBean = new GoodsBean(); goodsBean.setGoodsId(i); goodsBeans.add(goodsBean); } Integer totalProperty = 47;// TupleUtil<List<GoodsBean>, Integer> tupleUtil = new TupleUtil<List<GoodsBean>, Integer>(goodsBeans, totalProperty); TwoTuple<List<GoodsBean>, Integer> twoTuple = TupleUtil.tuple(goodsBeans, totalProperty); List<GoodsBean> list = twoTuple.first; System.out.println(list); System.out.println(twoTuple.second); }} |
Java Tuple使用執行個體(轉)