Guava将HashBasedTable投向TreeBasedTable。

问题描述 投票:0回答:1

我想把类com.google.common.collect.HashBasedTable投给com.google.common.collect.TreeBasedTable。

铸造不工作。

 class com.google.common.collect.HashBasedTable cannot be cast to class com.google.common.collect.TreeBasedTable

有什么有效的方法可以做到这一点?

guava guava-table
1个回答
1
投票

这是两个不同的 实施 用于通用 Table 因此,不能随便施放(类似于 ArrayListLinkedList但不能将一个表的内容复制到另一个表中)。)

然而,你可以将任何表的内容复制到一个新的表中,在你的情况下。

// Create sample HashBasedTable
Table<Integer, Integer, String> hashBasedTable = HashBasedTable.create();
hashBasedTable.put(1, 1, "eleven");
hashBasedTable.put(4, 2, "forty two");
hashBasedTable.put(2, 4, "twenty four");
hashBasedTable.put(1, 4, "fourteen");
  // {1={1=eleven, 4=fourteen}, 4={2=forty two}, 2={4=twenty four}}

// Create TreeBasedTable (with natural ordering, use `.create(Comparator, Comparator)` otherwise)
final TreeBasedTable<Comparable, Comparable, Object> treeBasedTable = TreeBasedTable.create();
treeBasedTable.putAll(hashBasedTable);
System.out.println(treeBasedTable);
  // {1={1=eleven, 4=fourteen}, 2={4=twenty four}, 4={2=forty two}}
© www.soinside.com 2019 - 2024. All rights reserved.