在java开发中,我们经常会遇到需要使用复杂数据结构的情况,例如在一个集合中存储另一个包含多种类型元素的集合。org.javatuples.pair 是一个非常实用的工具,它允许我们存储两个不同类型的对象。当我们将 pair 与 list 结合使用,例如 list
考虑以下场景:我们有一个 List,其中每个元素都是一个 Pair。这个 Pair 的第一个值是 Integer,第二个值是一个 List
以下代码片段展示了这种问题:
import org.javatuples.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List>> l;
l = new ArrayList<>();
l.add(new Pair<>(1, Arrays.asList(7, 9, 13)));
// 直接访问时,类型信息完整,List功能正常
System.out.println("直接访问 Pair.getValue0(): " + l.get(0).getValue0()); // 输出: 1
System.out.println("直接访问 Pair.getValue1(): " + l.get(0).getValue1()); // 输出: [7, 9, 13], 此时 .size() 可用
// 增强for循环中出现问题
System.out.println("\n--- 增强for循环中的问题 ---");
for (Pair p : l) { // 注意这里使用了原始类型 Pair
if (p.getValue0().equals(1)) {
// 此时 p.getValue1() 不再被编译器识别为 List
System.out.println("循环中访问 Pair.getValue1(): " + p.getValue1()); // 输出: [7, 9, 13]
// 尝试访问 p.getValue1().size() 会导致编译错误或运行时异常,
// 因为 p.getValue1() 返回的是 Object 类型
// 例如:System.out.println(p.getValue1().size()); // 编译错误
}
}
}
} 在上述代码中,当通过 l.get(0).getValue1() 直接访问时,List
问题的根源在于增强for循环中使用了 原始类型(Raw Type) Pair,而非带泛型参数的 Pair
Java的泛型在编译时会进行类型擦除。这意味着在运行时,List
对于原始类型 Pair,其 getValue0() 和 getValue1() 方法的返回类型都是 Object。因此,尽管运行时实际对象内部存储的是 Integer 和 List
解决此问题的关键在于,在增强for循环中为 Pair 变量明确指定其泛型参数。这样,编译器就能在编译时保留必要的类型信息,确保 p.getValue1() 被正确识别为 List
以下是修正后的代码:
import org.javatuples.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List>> l;
l = new ArrayList<>();
l.add(new Pair<>(1, Arrays.asList(7, 9, 13)));
System.out.println("直接访问 Pair.getValue0(): " + l.get(0).getValue0());
System.out.println("直接访问 Pair.getValue1(): " + l.get(0).getValue1());
System.out.println("\n--- 增强for循环中的正确用法 ---");
// 关键:在循环中为 Pair 指定完整的泛型参数
for (Pair> p : l) {
if (p.getValue0().equals(1)) {
// 此时 p.getValue1() 被编译器识别为 List
List nestedList = p.getValue1(); // 可以安全地赋值给 List
System.out.println("循环中访问 Pair.getValue1(): " + nestedList);
System.out.println("嵌套List的大小: " + nestedList.size()); // .size() 现在可以正常访问
System.out.println("嵌套List的第一个元素: " + nestedList.get(0)); // .get() 也可以正常访问
}
}
}
} 运行结果:
直接访问 Pair.getValue0(): 1 直接访问 Pair.getValue1(): [7, 9, 13] --- 增强for循环中的正确用法 --- 循环中访问 Pair.getValue1(): [7, 9, 13] 嵌套List的大小: 3 嵌套List的第一个元素: 7
通过将循环声明从 for (Pair p : l) 修改为 for (Pair
在Java中处理嵌套泛型结构时,如 List