Javatuples 简明教程

JavaTuples - Set Values

元组具有 setAtX() 方法来设置特定索引处的值。例如,Triplet 类具有以下方法。

A tuple has setAtX() methods to set value at particular index. For example Triplet class has following methods.

  1. setAt0() − set value at index 0.

  2. setAt1() − set value at index 1.

  3. setAt2() − set value at index 2.

Feature

  1. Tuples are immutable. Each setAtX() returns a new tuple which is to be used to see the updated value.

  2. Type of a position of a tuple can be changed using setAtX() method.

Example

让我们实际看看 JavaTuples。我们将了解如何使用各种方法在元组中设置值。

Let’s see JavaTuples in action. Here we’ll see how to set values in 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.Pair;
public class TupleTester {
   public static void main(String args[]){
      //Create using with() method
      Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5));
      Pair<String, Integer> pair1 = pair.setAt0("Updated Value");
      System.out.println("Original Pair: " + pair);
      System.out.println("Updated Pair:" + pair1);
      Pair<String, String> pair2 = pair.setAt1("Changed Type");
      System.out.println("Original Pair: " + pair);
      System.out.println("Changed Pair:" + pair2);
   }
}

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

Output

验证输出

Verify the Output

Original Pair: [Test, 5]
Updated Pair:[Updated Value, 5]
Original Pair: [Test, 5]
Changed Pair:[Test, Changed Type]