轉自鏈接:http://www.cnblogs.com/davidwang456/p/4514659.html
一、為什么使用元組tuple?
元組和列表list一樣,都可能用於數據存儲,包含多個數據;但是和列表不同的是:列表只能存儲相同的數據類型,而元組不一樣,它可以存儲不同的數據類型,比如同時存儲int、string、list等,並且可以根據需求無限擴展。
比如說在web應用中,經常會遇到一個問題就是數據分頁問題,查詢分頁需要包含幾點信息:當前頁數、頁大小;查詢結果返回數據為:當前頁的數據記錄,但是如果需要在前台顯示當前頁、頁大小、總頁數等信息的時候,就必須有另外一個信息就是:數據記錄總數,然后根據上面的信息進行計算得到總頁數等信息。這個時候查詢某一頁信息的時候需要返回兩個數據類型,一個是list(當前也的數據記錄),一個是int(記錄總數)。當然,完全可以在兩個方法、兩次數據庫連接中得到這兩個值。事實上在查詢list的時候,已經通過sql查詢得到總計錄數,如果再開一個方法,再做一次數據庫連接來查詢總計錄數,不免有點多此一舉、浪費時間、浪費代碼、浪費生命。言重了~在這種情況下,我們就可以利用二元組,在一次數據庫連接中,得到總計錄數、當前頁記錄,並存儲到其中,簡單明了!
二、源碼實例
二元組:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/** <p>Title: TwoTuple</p>
* <p>Description: 兩個元素的元組,用於在一個方法里返回兩種類型的值</p>
* @author Xewee.Zhiwei.Wang@gmail.com
* @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;
}
}
|
擴展為三元組(按此可以任意擴展)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/**
* <p>Title: ThreeTuple</p>
* <p>Description: 三個元素的元組,用於在一個方法里返回三種類型的值</p>
* @author Xewee.Zhiwei.Wang@gmail.com
* @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;
}
}
|
元組操作工具類、測試類(可按需自定義)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
import
java.util.ArrayList;
import
java.util.List;
import
com.bluesea.bean.GoodsBean;
/**
* <p>Title: TupleUtil</p>
* <p>Description:
* 元組輔助類,用於多種類型值的返回,如在分頁的時候,后台存儲過程既返回了查詢得到的
* 當頁的數據(List類型),又得到了數據表中總共的數據總數(Integer類型),然后將這
* 兩個參數封裝到該類中返回到action中使用
* 使用泛型方法實現,利用參數類型推斷,編譯器可以找出具體的類型
* </p>
* @author Xewee.Zhiwei.Wang@gmail.com
* @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);
}
}
|