關於方法的返回值,常常須要返回2個值或多個值的一個序列,好比數據表的一條記錄,文件的一行內容等。除了使用數組Array、集合(List、Set、Map)這些容器類型以外,在Java中咱們就必須建立一個Class來做爲返回類型。
在不少語言中都提供元組類型Tuple的支持,好比 .NET Framework 最多支持7個元素的元組,參考這裏: html
var population = new Tuple<string, int, int, int, int, int, int>( "New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278);
Scala最多支持22個元素的元組,參考這裏: java
val t = new Tuple4(4,3,2,1) val t = (4,3,2,1) // syntactic sugar val sum = t._1 + t._2 + t._3 + t._4
C++(STL)的Tuple,參考這裏: android
tuple<int, string, string> t(5, "foo", "bar"); cout << t.get<1>(); // outputs "foo"
先看看Java中若是想返回「一個」鍵值對Pair,該怎麼作?
(1)Apache Struts1的LabelValueBean git
LabelValueBean lv = new LabelValueBean("rensanning.iteye.com", "9527");
(2)Guava的Maps.immutableEntry github
Map.Entry<String,Integer> entry2 = Maps.immutableEntry("rensanning.iteye.com", 9527);
(3)Apache commons-collections的KeyValue apache
Map.Entry<String,Integer> entry3 = new DefaultMapEntry("rensanning.iteye.com", 9527); KeyValue<String,Integer> kv = new DefaultKeyValue("rensanning.iteye.com", 9527);
(4)Apache commons-lang3的Pair api
1 Map.Entry<String,Integer> entry4 = new ImmutablePair<String, Integer>("rensanning.iteye.com", 9527);
(5)Apache HttpClient的NameValuePair 數組
1 NameValuePair nv = new BasicNameValuePair("rensanning.iteye.com", "9527");
(6)Android的Pair oracle
1 Pair<String, Integer> p = new Pair<String, Integer>("rensanning.iteye.com", 9527);
。。。。。。等等還有不少,你也能夠本身擴展Map.Entry或者封裝Class。
Java 6提供AbstractMap.SimpleEntry<K,V>和AbstractMap.SimpleImmutableEntry<K,V> ui
1 Map.Entry<String,Integer> entry1 = new AbstractMap.SimpleEntry<String, Integer>("rensanning.iteye.com", 9527);
把這兩個Entity做爲靜態來嵌入到標示爲abstract的AbstractMap裏,這個API給的是至關的奇怪!
javatuples是一個很簡單的lib,它沒有什麼華麗的功能,就是提供了支持返回多個元素的一些類。
https://github.com/javatuples/javatuples
版本:javatuples-1.2.jar
最多支持10個元素:
經常使用的2元組Pair:
1 // 1元組 2 Unit<String> u = new Unit<String>("rensanning.iteye.com"); 3 // 2元組 4 Pair<String,Integer> p = Pair.with("rensanning.iteye.com", 9527); 5 // 3元組 6 Triplet<String,Integer,Double> triplet = Triplet.with("rensanning.iteye.com", 9527, 1.0); 7 //... 8 9 KeyValue<String,String> kv = KeyValue.with("rensanning.iteye.com", "9527"); 10 LabelValue<String,String> lv = LabelValue.with("rensanning.iteye.com", "9527");
參考連接:
http://tech.puredanger.com/2010/03/31/do-we-want-a-java-util-pair/
http://mail.openjdk.java.net/pipermail/core-libs-dev/2010-March/003995.html