Javatuples 简明教程
JavaTuples - Get Values
元组具有 getValueX() 方法来获取值,以及 getValue() 方法来通过索引获取值。例如,Triplet 类具有以下方法。
A tuple has getValueX() methods to get values and getValue() a generic method to get value by index. For example Triplet class has following methods.
-
getValue(index) − returns value at index starting from 0.
-
getValue0() − returns value at index 0.
-
getValue1() − returns value at index 1.
-
getValue2() − returns value at index 2.
Feature
-
getValueX() methods are typesafe and no cast is required, but getValue(index) is generic.
-
A tuple has getValueX() methods upto element count. For example, Triplet has no getValue3() method but Quartet has.
-
Semantic Classes KeyValue and LabelValue has getKey()/getValue() and getLabel()/getValue() instead of getValue0()/getValue1() methods.
Example
让我们实际看看 JavaTuples。我们将了解如何使用各种方法从元组获取值。
Let’s see JavaTuples in action. Here we’ll see how to get values from a tuple using various ways.
在 C:>JavaTuples 中创建一个名为 TupleTester 的 Java 类文件。
Create a java class file named TupleTester in C:\>JavaTuples.
文件:TupleTester.java
File: TupleTester.java
package com.tutorialspoint;
import org.javatuples.KeyValue;
import org.javatuples.Pair;
public class TupleTester {
public static void main(String args[]){
//Create using with() method
Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5));
Object value0Obj = pair.getValue(0);
Object value1Obj = pair.getValue(1);
String value0 = pair.getValue0();
Integer value1 = pair.getValue1();
System.out.println(value0Obj);
System.out.println(value1Obj);
System.out.println(value0);
System.out.println(value1);
KeyValue<String, Integer> keyValue = KeyValue.with(
"Test", Integer.valueOf(5)
);
value0 = keyValue.getKey();
value1 = keyValue.getValue();
System.out.println(value0Obj);
System.out.println(value1Obj);
}
}
Verify the result
Verify the result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
现在运行 TupleTester 查看结果:
Now run the TupleTester to see the result −
C:\JavaTuples>java -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester