有時需要在方法末尾返回類型不同的對象,而return 語句只能返回一個或一組類型一樣的對象。此時就需要用到泛型。
首先先解釋個概念,
元組:它是將一組對象直接打包存儲于其中的一個單一對象,這個容器對象允許讀取其中元素,但不能修改。
利用泛型創建元組
1
2
3
4
5
6
7
8
9
10
11
|
public class ReturnTwo<A,B> { public final A first; public final B second; public ReturnTwo(A a,B b) { first = a; second = b; } } |
測試
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class Test { private String a = "abc" ; private int b = 123 ; public ReturnTwo<String, Integer> get() { ReturnTwo<String, Integer> rt = new ReturnTwo<String, Integer>( this .a, this .b); return rt; } public static void main(String[] args) { Test test = new Test(); ReturnTwo<String, Integer> rt = test.get(); System.out.println(rt.first); System.out.println(rt.second); } } |
輸出結果:
abc
123
以上這篇JAVA利用泛型返回類型不同的對象方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。