Guava cast HashBasedTable to TreeBasedTable

101 Views Asked by At

I am looking to cast class com.google.common.collect.HashBasedTable to com.google.common.collect.TreeBasedTable.

Casting does not work.

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

Is there an efficient way to do this ?

1

There are 1 best solutions below

0
Grzegorz Rożniecki On

These are two different implementations for generic Table and thus cannot just be cast (similarly to ArrayList and LinkedList, which cannot be case one to another).

You can however copy contents of any table to a new one, in your case:

// 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}}