在Java中,Pair(对)是一个用于存储两个对象的数据结构。要使用Pair,可以按照以下步骤进行操作:
- 导入Pair类所在的包(通常是
org.apache.commons.lang3.tuple
):
import org.apache.commons.lang3.tuple.Pair;
- 创建Pair对象并指定两个对象的值:
Pairpair = Pair.of("hello", 10);
- 获取Pair中的值:
String firstValue = https://www.yisu.com/ask/pair.getLeft();>或者可以使用
getFirst()
和getSecond()
方法来获取值。
- 可以通过修改Pair对象的值来更新其中的值:
pair.setLeft("world"); pair.setRight(20);完整示例:
import org.apache.commons.lang3.tuple.Pair; public class PairExample { public static void main(String[] args) { Pairpair = Pair.of("hello", 10); String firstValue = https://www.yisu.com/ask/pair.getLeft();"First value: " + firstValue); // 输出:First value: hello System.out.println("Second value: " + secondValue); // 输出:Second value: 10 pair.setLeft("world"); pair.setRight(20); firstValue = https://www.yisu.com/ask/pair.getLeft();"First value: " + firstValue); // 输出:First value: world System.out.println("Second value: " + secondValue); // 输出:Second value: 20 } }